Fetch array with $wpdb

wpdb‘s get_results method takes an optional second argument that lets you specify how the data is returned. The default return is an object. But you can also set it to…

OBJECT – result will be output as a numerically indexed array of row objects.

OBJECT_K – result will be output as an associative array of row objects, using first column’s values as keys (duplicates will be discarded).

ARRAY_A – result will be output as an numerically indexed array of associative arrays, using column names as keys.

ARRAY_N – result will be output as a numerically indexed array of numerically indexed arrays.

(from the codex)

You probably want ARRAY_A.

<?php
$query = $wpdb->get_results("SELECT * FROM videos", ARRAY_A);

Unfortunately, wpdb doesn’t allow you to “stream in” results like you’re doing, so you’ll need to use a foreach loop.

<?php
foreach($query as $row)
{
    // do stuff with $row here.
}

Leave a Comment