Query error

0

What's wrong?

I did everything right, I researched and it retakes the error to me:

Notice: Trying to get property 'num_rows' of non-object in C:\xampp\htdocs\tipo\consulta-online.php on line 21

What can it be?

<?php

    $servidorBanco = "localhost";
    $usuarioBanco = "root";
    $senhaBanco = "12345";
    $dadosBanco = "bancodedados";

    $conexao = mysqli_connect($servidorBanco, $usuarioBanco, $senhaBanco, $dadosBanco);

    if(!$conexao){
        die("Falha na conexao: " . mysqli_connect_error());
    }else{
        //echo "Conexao realizada com sucesso";
    }   

    $sql = "SELECT * FROM sis_clientes";
    $result = $conexao->query($sql);

    if ($result->num_rows > 0) {

       while($row = $result->fetch_assoc()) {

           //É isso que eu quero que consulta, quero que consulte 
           //todos os dados refere a esse campo da tabela "login"
           echo $row["login"];

        }
    } else {
        echo "0 results";
    }
    $conexao->close();
?>
    
asked by anonymous 11.03.2018 / 03:55

1 answer

1

This error happens when there is an query error.

The method query of extension MySQLi , can return 3 results:

  • false : In case of failure, for example, when query is invalid;
  • MySQLi_Result : If successful for queries type SELECT , SHOW , DESCRIBE or EXPLAIN ;
  • true : If successful for queries other than those mentioned in the previous item, for example, insert and update .

When we use a valid query , however, with the name of the table or different fields, the query method returns us a false and therefore we can not access the property as num_rows .

So it's important to use verification with mysqli_error or $conn->error . Obviously it is necessary to use this practice with care. Ideally, you store these values in a log and treat the message to the client, for example:

<?php

$conexao = mysqli_connect("localhost:3307", "root", "123456", "teste");

$sql = "SHOW TABLE;"; /* Erro proposital */
$result = $conexao->query($sql);

if ($conexao->error) {
    Log::warning( $conexao->error );
    die("Não foi possível completar a operação. Entre em contato com um adminstrador do site.");
}

This will prevent malicious people from getting errors from your application. So, only you, developer, will know the errors and can correct them in your application.

    
11.03.2018 / 04:32