Atef Sugair
Atef Sugair

Reputation: 35

php loop start over when num_rows==0

I'm trying to write a php code to select form tables:

  1. books
  2. images

Some books does not have an image, so I want to skip it and select another book. I have wrote this code but it does not work with me perfectly.

Now I'm getting only 5 records! it must be 6 as I limited in the book select query.

$slider_sql = "select * from books  limit 6";
$slider_result = $conn->query($slider_sql);
while($slider_row = $slider_result->fetch_assoc()) {
   extract($slider_row);

   $img_sql = "SELECT big_img FROM images WHERE book_id = '$id'";
   $img_rs = $conn->query($img_sql);
   $img_row = $img_rs->fetch_assoc();

   if ($img_rs->num_rows == 0) 
       continue; //--> here I want to start while again to select another book.
    echo $book_name.'<br>';
    echo $img_row['big_img'].'<br>';
} 

Thanks for your help and time!

Upvotes: 2

Views: 296

Answers (1)

Qirel
Qirel

Reputation: 26480

Instead of having a sub-query in a loop (which is nearly ALWAYS a bad idea!), use a JOIN instead, which simplifies it to one query instead of two. Then set a condition that big_img should not be empty. This guarantees that you will only find rows where there's an image matching the book. LIMIT will still only ensure the return of 6 rows. <> in MySQL is the same as !=.

$slider_sql = "SELECT b.book_name, i.big_img 
               FROM books b 
               JOIN images i 
                 ON i.book_id=b.id 
               WHERE i.big_img <> '' 
               LIMIT 6";
$result = $conn->query($slider_sql);
while ($row = $result->fetch_assoc()) {
    echo $row['book_name'].'<br>';
    echo $row['big_img'].'<br>';
} 

Upvotes: 3

Related Questions