How do I fetch each row as an associative array using $wpdb?

admin2025-01-07  4

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'] == "/".end(explode('/',$row['video'])) ) {
            $data[$row['id']] = end(explode('/', $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.

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 edited Nov 29, 2024 at 8:37 Flimm 7107 silver badges25 bronze badges asked Nov 26, 2012 at 19:25 MarkMark 3511 gold badge4 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 32

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.
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736265564a1054.html

最新回复(0)