1

I have a $wpdb query that will always only return one result. This is a simplified version of it:

$results = $wpdb->get_results ( "SELECT name FROM testTable WHERE id=1" );  

Do I have to use foreach to get that single result?

foreach ($results as $result ) {
   $name = $result->name;
}

Or can I skip the foreach and instead do something like this:

$name = $result->name[0];
5

Read the Codex:

The get_var function returns a single variable from the database. Though only one variable is returned, the entire result of the query is cached for later use. Returns NULL if no result is found.

<?php $wpdb->get_var( 'query', column_offset, row_offset ); ?> 

So for you its:

$name = $wpdb->get_var("SELECT name FROM testTable WHERE id=1");

If you want a row use get_row:

To retrieve an entire row from a query, use get_row. The function can return the row as an object, an associative array, or as a numerically indexed array. If more than one row is returned by the query, only the specified row is returned by the function, but all rows are cached for later use. Returns NULL if no result is found, consider this when using the returned value in arguments, see example below.

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.