Home » Php » wordpress – Using WPDB to connect to external database for inserting dynamic form data with php

wordpress – Using WPDB to connect to external database for inserting dynamic form data with php

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have an external database where I want my form data to be inserted to with $wpdb. On the page where the form resides, I am able to declare $wpdb as a global and then do a newdb to pull results and echo them into my form.

This code currently works:

<?php
global $wpdb;
$member_id = SwpmMemberUtils::get_logged_in_members_id();
$field_name = 'user_name';
$fname_value = SwpmMemberUtils::get_member_field_by_id($member_id, $field_name); 

    $newdb = new wpdb( 'user' , 'pass' , 'database' , 'localhost' );
    $newdb->show_errors();
$results = $newdb->get_results($wpdb->prepare("SELECT * FROM member_lists WHERE username = %s",$fname_value));
?>

For the submit form action, I have a PHP file named update-list.php that I have in my theme child folder to do the insert for my post data which is not working. I am getting this error:

Fatal error: Uncaught Error: Class ‘wpdb’ not found in /home/site/www/www/home/wp-content/themes/Avada-child/update-list.php:4 Stack trace: #0 {main} thrown in /home/site/www/www/home/wp-content/themes/Avada-child/update-list.php on line 4

Here is the code for that update-list.php file:

<?php

global $wpdb;
$newdb = new wpdb( 'user' , 'pass' , 'database' , 'localhost' );

$stats = array();
for( $i = 0; $i <= $stats; $i++ ) 
{
    $stats[] = array(
        'username' => $_POST['username'],
        'first_name' => $_POST['first_name'],
        'last_name' => $_POST['last_name'],
        'county' => $_POST['county'],
        'street' => $_POST['street'],
        'city' => $_POST['city'],
        'ward' => $_POST['precinct'], 
    );
}

foreach ( $stats as $stat )
    $newdb=$wpdb->insert( 'member_lists', $stat );


?>

Why does it recognize wpdb on the page with my form but not in the form action update-list.php file?

How to&Answers:

This sounds like something you should be Using AJAX for (which would eliminate the issue at hand).

With that said, your issue as it stands is because you’re POSTing to essentially an arbitrary PHP file that has no knowledge of WordPress. Since it wasn’t loaded into the request with WordPress methods, you’ll need to load up WordPress yourself. Take a look at this WPSE answer.

Basically, at a minimum, you’ll need to add require_once '/path/to/your/wp-load.php'; at the top of your update-list.php file before you can use anything ‘WordPress’, including $wpdb.