I have managed after a struggle to understand what is happening with the prepare placeholders. My only thought is that my table does not have a consistent element in it that I can use as a reference with the place holder.
There is a test column that I have used, but i do not intend on having it in my production plugin. The column is set to 0 for each entry, and I set the $test to 0. Thus my query has now started working. But this doesn't really make sense as a security feature unless it is dynamically calling something in reference to the results on the database. The examples I have seen around all rely on a set constant in their query, but I haven't got this unless I just add a constant entry in the database, but this seems silly.
$test = 0;
$result =
$wpdb->get_results( $wpdb->prepare
( "SELECT * FROM $my_noted_table_name WHERE id_can_view = %d ", $test));
Is there a better way of doing this?
Thanks in advance..
Let me explain what is happening.
The
prepareis sanitizing the variable's value, inserting it where you specified the placeholder, and then formatting the SQL query. Then the returned SQL query string is processed by the$wpdb->get_results().Step 1:
For this line of code:
here's what is happening:
$test$my_noted_table_namevariable.For the placeholder,
%dmeans the value will be an integer. If it's a string, then use%sinstead. Think about it in terms of using the PHP constructsprintforprintf.So, let's say your variable
$testhas a value of 100 assigned to it and the database table's name iscountries. Then SQL query string then is:See how
$wpdb->preparetransformed your inputted string into a properly formatted SQL query?You want to ALWAYS use
$wpdb->prepare()to handle this process as it will protect your database.