Search code examples
phpwordpressmultidimensional-arrayresultset

$wpdb->get_results() as an array of arrays


I am adding an ancillary page to my wordpress site ( without the site's styling, menu, etc ) using the following template and it is not returning any results from the database. I've read countless web pages and a couple of WP books and I am at a lost. I can see the four records in the database but the page shows none. Here's my template:

<?php /* Template Name: Media Player Page */ ?><!DOCTYPE html> > <head> <meta charset="<?php bloginfo('charset'); ?>" /> <title>Online Media Player</title>

    <?php wp_head(); ?>

    <link rel="stylesheet" href="/assets/css/music-player.css" type="text/css" media="screen" charset="utf-8">

    <script src="/assets/js/jquery-1.8.3.js"></script>
</head>

<body>
    <div class="main-center">
        <h1>Please select your choice of music</h1>
        <?php
            global $wpdb;
            $rows = $wpdb->get_results("select * from ppm_playlists");
            foreach($rows as $row) :
        ?>
            <a class="openplayer"  data-genre="<?php echo $row['id']; ?>" href="#"><?php echo $row['playlist']; ?></a>
        <?php endforeach; ?>
    </div> <!-- /.main-center -->

    <script type="text/javascript">
        (function($) {
            $('.main-center').on('click', '.openplayer', function(e){
                var genre = $(this).data('genre');
                e.preventDefault();
                alert(genre);
            });
        })(jQuery);
    </script>
</body> </html>

Solution

  • $wpdb->get_results will return an array of objects, not an array of arrays, unless you pass it a second parameter instructing otherwise. If you had debugging enabled, you would see Fatal Error: Cannot use object of type stdClass as array....

    You want to be using object syntax:

    foreach($rows as $row) : ?>
      <a class="openplayer"  data-genre="<?php echo $row->id; ?>" href="#"><?php echo $row->playlist; ?></a>
    <?php endforeach; ?>
    

    Or pass a second parameter to get_results

    $rows = $wpdb->get_results("select * from ppm_playlists", ARRAY_A);