Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm new to SQL and am wondering if I need to use wpdb->prepare for the following query to a table I've created

global $wpdb;
$tablename = $wpdb->prefix . "my_custom_table";
$sql = "SELECT * FROM " . $tablename . " ORDER BY date_created DESC";
$resulst = $wpdb->get_results( $sql , ARRAY_A );

Do I need to use prepare here? How would I do that?

Cheers

share|improve this question

1 Answer 1

up vote 8 down vote accepted

Its best practice to always use prepare but the main use of it is to prevent against SQL injection attacks, and since there is no input from the users/visitors or they can't effect the query then that is not an issue in your current example.

but like i said before its best practice to use it and once you start using it you never stop , so in your example you can use it like so:

global $wpdb;
$tablename = $wpdb->prefix . "my_custom_table";
$sql = $wpdb->prepare( "SELECT * FROM %s ORDER BY date_created DESC",$tablename );
$resulst = $wpdb->get_results( $sql , ARRAY_A );

to read more about how to use it head to the codex

share|improve this answer
    
Hi @Bainternet, thanks for such a clear explanation - for some reason when I try your code it returns an empty array. I've checked and doubled checked for typos. If I do the unprepared query I get the array. I don't understand why it's not working..! –  Richard Sweeney May 11 '11 at 8:03
    
Odd. I've tried using the same code with another query: $tablename = $wpdb->prefix . "my_custom_table"; $concert_id = 1; $sql = "SELECT * FROM " . $tablename . " WHERE concert_id = %d LIMIT 1;"; $prep_sql = $wpdb->prepare( $sql, $concert_id ); $get_concerts = $wpdb->get_results( $prep_sql , ARRAY_A ); And it works great! Not sure why that would be. But I get it now in any case! –  Richard Sweeney May 11 '11 at 8:36
2  
Enclosing the table name in single quotes will not work. The normal escaping is with backticks, so your query should end up looking like this: SELECT * FROM `wp_my_custom_table`. You can enable double quote support, but then it would have to look like this: SELECT * FROM "wp_my_custom_table". –  Jan Fabry May 11 '11 at 8:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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