• Resolved JukeBoxWhiz

    (@jukeboxwhiz)


    Trying to learn how retrieve data from a database for display on a wordpress page.

    I’m using the sakila database.

    I’m using this to display names:

    global $wpdb;  $customers = $wpdb->get_results("SELECT first_name FROM sakila.actor;");
    while($row[] = mysql_fetch_array( $customers )){
       echo $row[first_name];
    }

    Here is the error I get:

    Warning: mysql_fetch_array() expects parameter 1 to be resource, array given in C:\xampp\htdocs\wordpress\wp-content\themes\twentyfifteen\db-exp.php on line 28

    Isn’t $customers an array?

    Before I tried this code I was using this:

    <?php global $wpdb; $customers = $wpdb->get_results("SELECT first_name FROM sakila.actor;"); print_r($customers); ?>

    And it printed out the entire array of first names, but included meta data like Array[0]Penelope Array[1]Arnold… all the way through to the 200th item.

    So, I figure there is an array within the variable $customers. So why isn’t that a resource?

Viewing 2 replies - 1 through 2 (of 2 total)
  • You’re on the right track, but a bit off on the execution (but not by much!)

    Where you’ve gone wrong is in two places. Firstly, when you use $wpdb->get_results() you don’t need to use mysql_fetch_array (). All that’s done behind the scenes before you get the results back for that query. The second one is a possibility, but normally calls to $wpdb->get_results() returns an array of objects, not an array of arrays.

    So, with that in mind, try this:

    global $wpdb;
    
    $customers = $wpdb->get_results("SELECT first_name FROM sakila.actor;");
    
    foreach ($customers as $row) {
        echo $row->first_name;
    }
    Thread Starter JukeBoxWhiz

    (@jukeboxwhiz)

    Ahhhh, okay. Thanks.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘what's wrong with this php mysql code?’ is closed to new replies.