Parsing through results in WordPress Sql Query

I am fairly new and I am struggling with a simple WordPress SQL query on the standard database for a plugin I am developing.

I am using the following code to echo out the titles of the first 10 posts:

Read More
global $wpdb;
$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->posts LIMIT 0, 10;"));

$i = 0;
while($i < count($results)){
    echo $results->post_title;
    $i++;
}

But nothing is getting echo’d out to the screen. There are a more that 10 posts in the database so not having data is not the issue.

Related posts

Leave a Reply

1 comment

  1. I believe instead of this:

    $i = 0;
    while($i < count($results)){
        echo $results->post_title;
        $i++;
    }
    

    (Which will always echo the same variable), what you need to do is this:

    foreach ($results as $result) {
        echo $result->post_title;
    }
    

    Because $results is an array.

    You might be able to do this as well, but there’s no benefit over foreach:

    $i = 0;
    while($i < count($results)){
        echo $results[$i]->post_title;
        $i++;
    }