6

I have this code, but what I get in the browser are all the fields - even those stored as Int and Bool in SQL - as strings.

add_action( 'rest_api_init', function () {
  register_rest_route( 'restos/v1', '/resto/(?P<qname>.*)', array(
    'methods' => 'GET',
    'callback' => 'handle_get',
    'permission_callback' => function () {
      return current_user_can( 'edit_others_posts' );
    }
  ) );
} );

function handle_get( $data ) {
    global $wpdb;
    $query = "SELECT * FROM `restaurants` WHERE `qname` = '".$data['qname']."' LIMIT 1";
    $res = $wpdb->get_results($query)[0];

    return $res;
}

I tried return json_encode($res) but that did not help. How can I get an object sent over with numbers and booleans in json.

2
  • 2
    Info: Use wpdb->prepare wherever you can for placeholders
    – bravokeyl
    Apr 15, 2017 at 19:14
  • It's very important, as @bravokeyl suggests, to avoid possible SQL injections.
    – birgire
    Apr 15, 2017 at 19:20

1 Answer 1

3

The string output type is expected for $wpdb query results, the db data types are not mapped to the corresponding PHP data types.

You will have to take care of it yourself, like:

$data = [
    'int'    => (int)    '123',
    'bool'   => (bool)   '1',
    'string' => (string) 'abc'
];

return rest_ensure_response( $data );

with the rest response:

{"int":123,"bool":true,"string":"abc"}

Here's an interesting approach by Matthew Boynes, to handle it automatically in wpdb with a custom wrapper.

Note that you can use wpdb::get_row to get a single row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.