I'm just trying to query the first user, but it outputs this error,

WordPress database 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_users' WHERE ID = 1' at line 1] SELECT * FROM 'wp_users' WHERE ID = 1

And my code,

global $wpdb;


$sql = $wpdb->prepare( "SELECT * FROM %s WHERE ID = %d" , $wpdb->users, 1);
$results = $wpdb->get_results($sql);

echo '<pre>';
echo '</pre>';    

When you use $wpdb->prepare the placeholder %s is replaced with something between quotes, so, your query becomes:

"SELECT * FROM 'wp_users' WHERE ID = 1"

but table names in SQL queries must not be wrapped in quotes. So, the right way is:

$sql = $wpdb->prepare( "SELECT * FROM {$wpdb->users} WHERE ID = %d", 1 );
$results = $wpdb->get_results($sql);

Note that this may not work because nothing assure that exists an user with the id = 1. (Actually someone discourages to have user with ID = 1 for security reason).

If you want to pick first user is better to use something like:

$user = $wpdb->get_row( "SELECT * FROM {$wpdb->users} ORDER BY ID ASC LIMIT 1" );

In this way you get first user row, no matter what its ID is.

  • Is it "{$wpdb->users}" secure from SQL inyection? get_row() too?
    – autorun
    Aug 27 '14 at 6:55
  • You need to escape things for SQL injection when they comes from user input, $wpdb->users is just a string that comes from WordPress. If you want to enter paranoia mode you can use "{esc_sql( $wpdb->users )}". Also "{$wpdb->users}" is the way WordPress uses for internal queries, if it is insecure all WordPress is insecure. Regarding get_row is just another $wpdb method (see docs) that returns a single row instead of an array of rows. There is no reason that should make it more or less secure than get_results @autorun
    – gmazzap
    Aug 27 '14 at 7:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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