2

I am trying to fetch the post_id from the wp_postmeta table, here is the code I'm using:

if(isset($_POST['patientid'])) { //user enters the patientid

    $thevalue = $_POST['patientid'];
    $tbl = $wpdb->prefix.'postmeta';

    $prepare_guery = $wpdb->prepare( "SELECT post_id FROM $tbl WHERE meta_key ='patientid' AND meta_value LIKE $thevalue", $meta_value );

    $get_values = $wpdb->get_col( $prepare_guery );
    echo $get_values;
}

but this only prints out "Array", that's it.

Can anyone please tell me what I should change? Thank you!

1
  • $get_values isn't returned as a string by $wpdb, which is why you're seeing the string "Array" being echo'd. Try changing echo $get_values; to $get_values[0]->post_id.
    – WP Updoot
    Commented Nov 17, 2019 at 8:21

1 Answer 1

1

There's the WordPress meta API for retrieving meta values from the wp_postmeta table, but the API doesn't provide a function for retrieving the post ID (post_id value), but you can use custom SQL as in your code.

However, $wpdb->get_col() returns an array of values (upon success), so that's why you get the "Array" when you do echo $get_values;.

So you can either do something like this:

$post_ids = $wpdb->get_col( $prepare_guery ); // returns an array of IDs on success
$post_id = $post_ids[0]; // simplified - assuming that $post_ids[0] is actually set
var_dump( $post_ids ); // for testing

Or (a simpler option) if you want to retrieve just a single value, you should use $wpdb->get_var():

$post_id = $wpdb->get_var( $prepare_guery ); // returns a string (an ID) on success

Additional Notes

$prepare_guery = $wpdb->prepare( "SELECT post_id FROM $tbl WHERE meta_key ='patientid' AND meta_value LIKE $thevalue", $meta_value );

should be:

$prepare_guery = $wpdb->prepare( "SELECT post_id FROM $tbl WHERE meta_key ='patientid' AND meta_value LIKE %s", $wpdb->esc_like( $thevalue ) );

I.e. Note the %s (placeholder) and I also use $wpdb->esc_like(). I also realized that the $meta_value is not defined in your code, hence I changed that (in the above code) to $thevalue.

And in the previous revisions, I misspelled the $prepare_guery as $prepare_query... or did you mean $prepare_query ?

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.