0

I have a query where I get the highest id from a table.

$user_id = $wpdb->get_row("SELECT * FROM $table WHERE id=(SELECT MAX(id) FROM $table)")

The table should always have rows, but if for some reason it returns empty, there is an error (printed with $wpdb->print_error()):

WordPress database error: []

I was wondering why an empty result means an error? And how would I prevent this error?

3
  • What do you want to achieve? Maybe there´s another/a better way to do what you want...
    – flomei
    Commented Nov 5, 2015 at 12:48
  • Is this sub-query faster than ordering by ID with a LIMIT 0,1 ? What's the generated SQL query?
    – birgire
    Commented Nov 5, 2015 at 12:50
  • I get what I want with the query - I get the row with the highest id (the latest one). So it will always work. I just wanted to eliminate the possibility of errors, and if the the table is empty, the query returns 0 results, which is an error. I don't understand why it is an error.
    – Galivan
    Commented Nov 5, 2015 at 13:15

1 Answer 1

0

There isn't an error. The square brackets are empty-- aka "no error". Put a spurious comma in the SQL and you will see what I mean.

But your SQL is wildly complicated for you are doing. That is entirely equivalent to

SELECT * FROM $table ORDER BY id DESC LIMIT 1

Though, I notice you are using id rather than ID and I don't remember any Core tables using the lowercase version. If this is meant for a Core table that will be a problem.

1
  • Alright, great info! I use it for a custom table that I made. If there is no error, does it mean that $wpdb->print_error() will always display "WordPress database error" even when there is no error? That SQL statement looks nice, I didn't think about DESC LIMIT!
    – Galivan
    Commented Nov 5, 2015 at 15:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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