ngplayground
ngplayground

Reputation: 21667

PHP foreach and mysql within

foreach ($array as &$value) {
    $q3 = "SELECT * FROM wp_posts WHERE post_name = '$value'";
    $r3 = $wpdb->get_results($q3);
    $Idd = $r3[0]->ID;
    $img = wp_get_attachment_url( get_post_thumbnail_id($Idd, 'thumbnail') );
    //echo $value;
    //echo $Idd;
    //echo $img;
    $list .= '<li><img src="'.$img.'"/><br>'.$value.'</li>';
}

Using the above, if I echo $value my array is printed. if I echo $Idd the result instead of several ID's is just a singular and the same goes for $img

How can I run the above to work and print out the $img's and $Idd

Thanks

Upvotes: 0

Views: 60

Answers (1)

Kami
Kami

Reputation: 19457

You code is loading the first value of the result set and only using it.

If you need to display all the values, then you will need to loop over the results.

foreach ($array as &$value) {
    $q3 = "SELECT * FROM wp_posts WHERE post_name = '$value'";
    $r3 = $wpdb->get_results($q3);
    foreach ($r3 as $imgRes)
    {
      $Idd = $imgRes->ID;
      $img = wp_get_attachment_url( get_post_thumbnail_id($Idd, 'thumbnail') );
      $list .= '<li><img src="'.$img.'"/><br>'.$value.'</li>';
    }
}

Upvotes: 3

Related Questions