Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am trying to convert this code to use the $wpdb.

$data = array();

$query = "SELECT * FROM videos";
$query_exec = mysql_query($query) or die();

while($row = mysql_fetch_array($query_exec)) {
    if ( $row['video'] == "http://youtu.be/".end(explode('http://youtu.be/',$row['video'])) ) {
            $data[$row['id']] = end(explode('http://youtu.be/', $row['video']));
        } else {
            $data[$row['id']] = end(explode('?v=', $row['video']));
        }   
    }

So I did:

$query = $wpdb->get_results("SELECT * FROM videos");

But how can I fetch the array? Thank you in advance for the help.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

wpdb's get_results method takes an optional second argument that let's you specify out the data is return the default 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.
}
share|improve this answer
    
Ok, thanks. But what about this line? while($row = mysql_fetch_array($query_exec)) { –  Mark Nov 26 '12 at 19:43
    
See my edit, you just need to use a foreach loop instead of while. –  chrisguitarguy Nov 26 '12 at 19:45
    
Damn, I missed the ARRAY_A the first time, so I got an error in my foreach. Thank you very much. –  Mark Nov 26 '12 at 19:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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