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 sure this is a simple oversight but I cannot seem to narrow it down:

 global $wpdb;
 $tablename = $wpdb->prefix . "icrm_folders";
 $sql = $wpdb->prepare( "SELECT * FROM %s", $tablename );
 //$sql results in SELECT * FROM 'wp_icrm_folders'
 $result = $wpdb->get_results( $sql );

This seems to result in nothing! My debugger shows an error on $wpdb object under last_error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''wp_icrm_folders'' at line 1

Now I ran the query SELECT * FROM 'wp_icrm_folders' directly in phpmyadmin and that gives me an error because wp_icrm_folders is inside ' the query executes fine if I remove the apostrophes or replace them with the grave accent/character.

PHP Version 5.3.3-7

MySQL Version 5.1.63

WordPress 3.5.1

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

Don't use $wpdb->prepare with table names. prepare will quote your table names that will result in incorrect SQL.

It is unnecessary overhead as well. Your table name should never, and in your case isn't, be user-supplied data. You have no need to escape it. 'prepare' is for use on user-supplied data, such as data from a form or a $_GET parameter.

You have no user-supplied data so all you need is

$wpdb->get_results("SELECT * FROM {$tablename}");
share|improve this answer
    
So if I wanted to have $_GET parameters I would use: $wpdb->get_results(wpdb->prepare("SELECT * FROM {$tablename} WHERE folder_id = %d", $_GET['folder_id'])); as a simple example? –  Omar Mir Mar 29 '13 at 16:12
    
If I remember correctly, $_GET parameters are always strings so using %d may not work, unless you cast $_GET['folder_id'] to an integer first, but basically that is it. –  s_ha_dum Mar 29 '13 at 16:16
    
Awesome thanks! –  Omar Mir Mar 29 '13 at 16:49
add comment

I think that you are not write the query in proper way. So here is just little example may be it help you.

$myrows = $wpdb->get_results( "SELECT id, name FROM mytable" );

and that's it.

share|improve this answer
    
No that's definitely not it. Tried it - it doesn't solve the problem. –  Omar Mir Mar 29 '13 at 16:14
add comment

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.