Error when Count() less than 1

Asked

Viewed 77 times

-3

I have a code that checks how many records an sql query returns.

<?php
if ($results) { $total = count($results); }
if ($total > 0) {
  echo "<p>Encontramos " .count($results). " conteúdo(s) para a sua busca!</p>";
} else {
  echo "<p>Lamentamos mas nenhum conteúdo foi encontrado para a sua busca! Tente novamente...</p>";
}
?>

When you find 1 or more records the message to the user appears right. When nothing is found count() = 0 appears the following error:

Notice: Undefined variable: total in D: xampp htdocs armazemdahouse Publication.php on line 164 We are sorry but no content has been found for your search! Try again...

How do I solve?

  • What code is on the line 164 of publication.php ?. And how is the $results?

  • @Isac line 164 is if ($total > 0) {

2 answers

2

Bom Flávio.
I would do something like this!

public function verificaResultados($lista){
     if(isset($lista)){
       $total_results = count($lista);
       if($total_results <= 0){
         echo "nada encontrado";
       }else{
         echo "$lista";// ;D
        }
     } 
}

1

It does not find the $total variable because it does not enter if where the "$Results" is found and does not initialize the "$total".

So before I check if the variable "$Results" exists and if it is also an array to be counted.

<?php
if(isset($results)){
    $total = 0;
    if (is_array($results)) { 
        $total = count($results); 
    }else{
        $total = 1;
    }
    if ($total > 0) {
        echo "<p>Encontramos " .count($results). " conteúdo(s) para a sua busca!</p>";
    } else {
        echo "<p>Lamentamos mas nenhum conteúdo foi encontrado para a sua busca! Tente novamente...</p>";
    }
}else{
    echo "<p>Lamentamos mas nenhum conteúdo foi encontrado para a sua busca! Tente novamente...</p>";
}
?>
  • when Count() less than 1 the variable is not set correctly, that must be the eerro then.

  • That’s exactly what happens.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.