WordPress.org

Ready to get started?Download WordPress

Forums

Custom List Table Example
Help using plugin (error message with sql instead of example $da (3 posts)

  1. redconservatory
    Member
    Posted 2 years ago #

    I've installed the plugin and it works great with the example data.

    However, when I try to use my own sql in the prepare_items function I am getting an error:

    Fatal error: Cannot use object of type stdClass as array

    It seems like the example data is an array that contains arrays
    i.e.

    var $example_data = array(
                array(
                    'ID'        => 1,
                    'title'     => '300',
                    'rating'    => 'R',
                    'director'  => 'Zach Snyder'
                ),
                array(
                    'ID'        => 2,
                    'title'     => 'Eyes Wide Shut',
                    'rating'    => 'R',
                    'director'  => 'Stanley Kubrick'
                ),

    But when I write:

    global $wpdb;
    		  $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'name'; //If no sort, default to title
              $sql = "SELECT * FROM wp_nc_location ORDER BY " . $orderby;
    		  $data = $wpdb->get_results($sql);

    My $data is an array that contains objects, print_r and gettype on $data reveals

    data is Array ( [0] => stdClass Object ( ...) [1] => stdClass Object ( ...) )

    Can anyone help?

    http://wordpress.org/extend/plugins/custom-list-table-example/

  2. redconservatory
    Member
    Posted 2 years ago #

    Wait, it appears that switching it from an object to an array helped:

    function column_default($item, $column_name){
    $item = (array)$item;
    }

    Is that considered a 'hack' way of doing this, or is this all right?

  3. Matt van Andel
    Member
    Plugin Author

    Posted 2 years ago #

    Casting some types of objects as arrays is technically valid.

    You can also specify what output type (object vs array) you want get_results() to return, so that no additional casting is necessary. Like so:

    $data = $wpdb->get_results($sql, ARRAY_A);
    

    This example returns an indexed array of all records, and the records themselves are associative arrays (just like the sample data used in the plugin).

    Take a look at this codex entry for more ideas >>

Topic Closed

This topic has been closed to new replies.

About this Plugin

About this Topic