Database interactions with WP_Query and $wpdb

Introduction to WordPress database objects for developers

WordCamp Asheville 2015

WordPress.tv Video


1 Thoughts

Discussion

Andre Harden
December 18, 2016

Hello Jonathan!
Quick question:

I’m trying to use JQuery /PHP to access data from an additional, custom table I created, but I keep getting “Array0” as the result.

Here is my code in functions.php:

add_action( ‘wp_ajax_verify_client’, ‘verify_client’ );
//Verify to see if client already exists
function verify_client(){
global $wpdb;
$result = $wpdb->get_row(“SELECT * FROM `verify’`”);
echo $result;

What am I doing wrong?

Thank you in advance,

Jonathan Daggerhart
December 18, 2016

Hi Andre,

I see a few issues here. You’re getting “Array” because the $result PHP variable isn’t a string, and the “0” because the ajax callback doesn’t exit;. You need to echo the $result variable as JSON, and then end PHP execution.

Luckily WordPress has a function that does both of those things: wp_send_json()

Try something like this:

add_action( 'wp_ajax_verify_client', 'verify_client' );

//Verify to see if client already exists
function verify_client(){
  global $wpdb;
  $result = $wpdb->get_row("SELECT * FROM `verify`");
  wp_send_json( $result );
}

Also, checkout the wp_send_json Codex page for an example using the data in jQuery.

Leave a Reply

Your email address will not be published. Required fields are marked *