Wordpress - How to parse row results from $wpdb -> get_results
foreach( $wpdb->get_results("SELECT * FROM your_table_name WHERE id LIKE' . $id . ';") as $key => $row) {
// each column in your row will be accessible like this
$my_column = $row->column_name;}
More info here
To use as an associative array:
$obj=[];
$rows = $wpdb->get_results( 'SELECT * FROM `tbl_name` WHERE `id` = '.$obj_id , ARRAY_A);
foreach($rows as $row){ $obj=$row; break; }
// $obj is now the selected row if a match was found
Usage
$something = $obj['column_name'];
foreach($obj as $col => $val)
echo $col . ': ' . $val . PHP_EOL . '<br />';
To get other formats, simply change ARRAY_A
based on the documentation for $wpdb->get_results()
. Pippin's answer is appropriate for most object use.
To use one row as an numerically indexed array
$rows = $wpdb->get_results( 'SELECT * FROM `tbl_name` WHERE `id` = '.$obj_id , ARRAY_N);
foreach($rows as $row){ $obj=$row; break; }
//Usage
foreach($obj as $col_value) echo $col_value . ' ';
To use one row in an array whose keys are the primary key from your database(often an id
column). Possibly more efficient than the associative array method.
$rows = $wpdb->get_results( 'SELECT * FROM `tbl_name` WHERE `id` = '.$obj_id , OBJECT_K);
$obj = $rows[ $obj_id ];
//Usage
$something = $obj->column_name;
//Remember you can loop over objects too
foreach($obj as $col => $val)
echo $col . ': ' . $val . PHP_EOL;
Always Try the WordPress Codex: http://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results
Essentially given the default syntax, the variable $row here is an object containing your results. You could alternately specify the TYPE of result (numeric array, associative array).
Assuming just one result, then $row->id and $row->name should give you the information.
If you get back more than one result, you'd want to loop over the entries in the object.
If you are expecting just one row back, then try using $wpdb->get_row http://codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Row