How to retrieve wp_ json_encode data from custom WordPress database table

$wpdb->get_results() returns an Array of rows representing the results. The rows themselves can be represented as objects or arrays depending on the second argument.

See the documentation:

output_type
One of four pre-defined constants. Defaults to OBJECT. See SELECT a Row and its examples for more information.

  • OBJECT – result will be output as a numerically indexed array of row objects.
  • OBJECT_K – result will be output as an associative array of row objects, using first column’s values as keys (duplicates will be
    discarded).
  • ARRAY_A – result will be output as a numerically indexed array of associative arrays, using column names as keys.
  • ARRAY_N – result will be output as a numerically indexed array of numerically indexed arrays.

So when you run your query, you’re going to get an array, with one element in it that is an object with a property reward_details that contains the JSON.

So without changing your query, you’d access the JSON with:

$someArray = json_decode( $string[0]->reward_details, true);

The key bit being $string[0]->reward_details. That’s where the value is.

wpdb has a better method for getting a single cell like this though, called get_var():

$query = $wpdb->prepare( 
    "SELECT
        reward_details
    FROM 
        wpxa_rewards 
    WHERE 
        project_id = %d
    ", 
    $project_id
);

$string = $wpdb->get_var( $query );

$someArray = json_decode( $string );

get_var() basically does the [0]->reward_details part for you.

Also note that I have used $wpdb->prepare for inserting the project ID into the query. You shouldn’t put user data directly into a query like you did in the original query.

Leave a Comment