I’m trying to run an SQL statement on a WordPress page. I’ve already tested it in the phpmyadmin and that works:
SELECT post_id FROM wp_postmeta WHERE meta_value = "9bf2c7f9760393fa83e65ad455e00243"
The result on this is the post_id 20
This is my code in the WordPress template:
<?php
global $wpdb;
$uniqueId = $_GET['id'];
$getPostId = $wpdb->get_var(
$wpdb->prepare("SELECT post_id FROM " . $wpdb->prefix . "wp_postmeta WHERE meta_value = %d", $uniqueId)
);
echo $getPostId;
?>
It should echo the value 20, but it does nothing. I’ve also tested if the variable $uniqueId
is set and that’s the case.
2
Answers
The %d placeholder in the prepare statement expects an integer. But you are assigning a string. So in this case you should use the string placeholder which is %s.
New code:
There are two problems with your code.
1. You have a typo in your query:
Should be:
You’re repeating the
wp_
prefix twice:2. As Mike pointed out,
%d
expects an integer. Your code suggests it should be a string so you should be using%s
instead:Updated code: