Pergunta

I am performing a routine to check if books exist in a database given a range. I want to echo if no books are found. I have the following:

$search = mysqli_query($con,$query);

while(list($book_id, $title, $authors, $description, $price) = mysqli_fetch_row($search)){

if(!empty($book_id)) {

echo "Book ID: " . $book_id . "<br/>";
echo "Book Title: " . $title . "<br/>";
echo "Authors: " . $authors . "<br/>";
echo "Description: " . $description . "<br/>";
echo "Price: " . $price . "<br/>";
echo "<br/>";

}

if(empty($book_id)){
    echo "Fail";
    }
}

If no books are found nothing is printed. The echo does not work? How come?

Thanks

Foi útil?

Solução

Because if no records are returned, you won't enter in the while at all, as $book_is will contain the value false and while(false)... you know

In this situation you may use mysqli_num_rows to check if there are rows found

Outras dicas

Your no results echo is inside the while loop which will never get called

while (list($book_id, $title, $authors, $description, $price) = mysqli_fetch_row($search)) {

  if (!empty($book_id)) {
    echo "Book ID: " . $book_id . "<br/>";
    echo "Book Title: " . $title . "<br/>";
    echo "Authors: " . $authors . "<br/>";
    echo "Description: " . $description . "<br/>";
    echo "Price: " . $price . "<br/>";
    echo "<br/>";
  }

}

if (empty($book_id)) {
  echo "Fail";
}

Move it outside like the code above

It is because your while loop has not been accessed at all. Try to echo something out of the if conditions, and see if it get's displayed.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top