Display message after MYSQL query return empty

Asked

Viewed 6,114 times

1

I have a script that makes a query in the database and displays the result...

I would like when the query returns empty, a message is displayed to the user.

The code:

<?php

//variavel dinamica
$chave = $_POST['chave'];

// Inclui a conexão PDO
include 'conexao_sup.php';

// Cria a consulta para o MySQL e executa
$consulta = $conexao->query("SELECT * FROM `pecas` WHERE codigo like '%".$chave."%' or descricao like '%".$chave."%' or aplicacao like '%".$chave."%'");


//Mostra os valores-----------------------------------

//exibe mensagem se a variável dinâmica vier vazia
if (empty($chave)){
    echo "<p style='color:#333; font-size:26px;'><b>Não foi digitado nada para a busca!</b></p>";
}

//exibe a consulta
else{

    while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)){ 
    ?>

    //retorno formatado em HTML

    <?php
    }
}
?>

How do I now implement a condition where:
If $query is empty...display message: "nothing found" ?

  • Create an IF to check if $consulta returns null or not, or inside the while if $linha is null or not...

  • I tried, but those conditions didn’t work.

3 answers

2

Just create a condition if the collection is empty:

<?php

require_once "conexao_sup.php";

if (isset($_POST['chave'])) {
    buscarDados($_POST['chave']);
} else {
  //exibe mensagem se não tiver nada enviado
   echo "<p style='color:#333; font-size:26px;'>".
        "<b>Digite uma palavra para fazer a busca!</b></p>";
}

function buscarDados($chave = '') {

    //exibe mensagem se não tiver ao menos 3 caracteres
    if (strlen($chave) < 3) {
        echo "<p style='color:#333; font-size:26px;'>".
             "<b>Digite ao menos 3 caracteres para fazer a busca!</b></p>";
        return;
    }

    // Cria a consulta para o MySQL e executa
    $consulta = $conexao->query("SELECT * FROM `pecas`
                                 WHERE codigo like '%".$chave."%'
                                 OR descricao like '%".$chave."%'
                                 OR aplicacao like '%".$chave."%'");
   $collection =  $consulta->fetchAll();

   if (count($collection) == 0 || !empty($collection)) {
      echo "<p style='color:#333; font-size:26px;'>" . 
           "<b>Não existem registros para o termo: {$chave}!</b></p>";
      return;
   } else {
   //Mostra os valores-----------------------------------
       foreach ($collection as $key => $value) {
           echo $value['codigo']    . '<br>' .
                $value['descricao'] . '<br>' .
                $value['aplicacao'] . '<br>';
       }
   }
}

1

Maybe this link will help you:

How to check if query-Results are Empty?

content of the Link.

$query= 'SELECT * FROM table'." WHERE id IS NOT NULL";

$result = mysql_query($query) or die ("Error in query: $query ".mysql_error());

$row = mysql_fetch_array($result);

$num_results = mysql_num_rows($result);

if ($num_results > 0){ 

echo $row['category']; 

}else{ 

echo 'no category' 

}
  • That answer was useful because it made me understand the logic that I was able to solve my problem.

1


With the reply of @Everson Moura I formulated the following logic:

1-Count the number of lines of the query 2-If the number of lines is == 0, then: displays message

My code stayed:

$chave = $_POST['chave'];

// Inclui a conexão PDO
include 'conexao_sup.php';

// Cria a consulta para o MySQL e executa
$consulta = $conexao->query("SELECT * FROM `pecas` WHERE codigo like '%".$chave."%' or descricao like '%".$chave."%' or aplicacao like '%".$chave."%'");

//atribui a variavel $row o total de linhas da consulta
$rows = $consulta->fetchAll();

//conta o tanto de linhas e atribui a variavel $num_rows
$num_rows = count($rows);

//Mostra os valores

if (empty($chave)){
    echo "<p style='color:#333; font-size:26px;'><b>Digite uma palavra para fazer a busca!</b></p>";
}else if($num_rows == 0){
    echo "<p style='color:#333; font-size:26px;'><b>Não existem registros para o termo: <font color='red'>{$chave}</font>!</b></p>";
}else{

//exibe consulta

}

Thank you all.

  • was exactly what I said in the comment of the first post.

Browser other questions tagged

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