0

I am saving a post id in a variable with the_id() function. And then i need to fetch the data of same post id from database . As post id is working fine but i am getting error while executing get result . below is the code . Can anyone please help ?

             $a = the_ID();; 
           global $wpdb;
            $data = $wpdb->get_results("SELECT `id`,`guid` FROM `wp_posts` WHERE `post_type` = 'local-offer' group by `post_author`");


            $result = $wpdb->get_results("SELECT * FROM `wp_postmeta` WHERE `post_id` = ".$a." ");
  • What is the error? Are you getting incorrect results? Empty results? Error values? PHP Warnings? PHP Errors? Note that you haven't called prepare so $a could be used in an SQL injection attack, have you considered just calling get_post_meta( $a )? Or using WP_Query? I see no reason whatsoever for you to be using raw SQL at all here, not to mention you're bypassing the object cache/pre-fetching so this may actually be a lot slower than using the APIs – Tom J Nowell Sep 15 '17 at 18:44
0

You have a typo

$a = the_ID(); 
$data = $wpdb->get_results("SELECT `id`,`guid` FROM `wp_posts` WHERE `post_type` = 'local-offer' group by `post_author`");
$result = $wpdb->get_results("SELECT * FROM `wp_postmeta` WHERE `post_id` = ".$a." ");
0

Your entire approach here is wrong, so lets break it apart line by line:

$a = the_ID(); 

the_ID echo's the post ID, this is not the correct function to use, instead use get_the_ID(). Notice that in WP functions beginning with the_ output data, and functions beginning with get_ return data.

$data = $wpdb->get_results("SELECT `id`,`guid` FROM `wp_posts` WHERE `post_type` = 'local-offer' group by `post_author`");

Here you're fetching post IDs from the post table where the post type is local-offer, grouped by post author, but this SQL query is unnecessary and slower! You're bypassing WP_Cache so it has to retrieve everything from scratch, and there's already an API for doing this, WP_Query:

$q = new WP_Query( [
    'post_type' => 'local-offer',
    'orderby' => 'author'
    'order' => 'ASC',
    'fields' => 'ids'
] );
$data = $q->posts;

Here we use WP_Query to fetch the posts, telling it to only fetch ID's, order by author, and only the local-offer post type, refer to the docs for more options, as well as using it to create a post loop for displaying things.

$result = $wpdb->get_results("SELECT * FROM `wp_postmeta` WHERE `post_id` = ".$a." ");

Here we have an SQL query to fetch all key value pairs for a given post ID, however:

  • there's no validation here, leaving you wide open to SQL injection attacks
  • there's already an easy API call for this!

You can replace this with:

$result = get_post_meta( $a );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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