I'm trying to get the number of records in one of my database tables where the post_id
field is equal to the $postID
variable I compare it to. When I swap {$postID}
out with an integer such as 130
, the query returns results as expected. However, whenever I try to query my DB using the $postID
variable, no results are returned. I've checked out what $postID
contains to ensure that post_id
is being compared to the right value, and it contains an integer value of 130
.
If the query works with a hardcoded 130
in place of $postID
, why doesn't it work when I use $postID
which is equal to 130
as well?
$postID = get_the_ID();
$postLikes = $wpdb->get_results('
SELECT COUNT(*) FROM wp_post_likes WHERE post_id = {$postID}
');
echo "<pre>";
var_dump($postLikes);
echo "</pre>";
Variable substitution does not take place in single quoted strings, see Variable parsing .
And I suggest you use a parameterized query instead of mixing the payload data into the actual statement, see Protect Queries Against SQL Injection Attacks
$postLikes = $wpdb->get_col($wpdb->prepare(
'SELECT COUNT(*) FROM wp_post_likes WHERE post_id = %s',
get_the_ID()
));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.