2

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:

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.

2
  • Have you tried foreach ($results as $result) echo $result->post_title? Cus I believe the code you have now would always echo the same thing. Also, turn on error reporting. Commented Jun 25, 2012 at 11:49
  • That worked, I tried with the foreach but couldn't really get my head around it thank you. If you post this as an answer i'll accept it. Commented Jun 25, 2012 at 11:53

1 Answer 1

2

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++;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.