I’ve a table in my database named wp_q33uds_campaign
. I have a query in my application as follows:
$usr = $wpdb->get_var('SELECT user_id FROM wp_q33uds_campaign WHERE date1 = 1451546940');
Now, this query returns a user_id
from the table which has the date1
column set as 1451546940
.
Now, somewhere in my application, I have a variable named $dd
where $dd
is set as 1451546940
. However, when I modify my above query as follows:
$usr = $wpdb->get_var('SELECT user_id FROM wp_q33uds_campaign WHERE date1 = $dd);
it returns a NULL
value. What seems to be wrong here? Is there no way to pass in PHP variables inside $wpdb
query?
You should use the
$wpdb->prepare()
method to properly escape variables to prevent syntax errors and most importantly to protect against SQL injection attacks – see Running General Queries in the WordPress documentation. You should also use the$wpdb->prefix
property to ensure the proper table prefix in your queries.The value you see for your date is actually a Unix timestamp, you will need to convert this to a string using
date()
;Use either
or
First, you are missing the close quote.
Second, when you use single quotes PHP take the string inside literal, so your $dd is not used as variable is used as string.
There are a lot of ways to fix this.
Or
The best way is using the
sprintf
http://php.net/manual/en/function.sprintf.phpIf you want your PHP var to be evaluated, you need to use doublequotes. Otherwise you need to concat your var with your string like this