I'm just getting started in PHP, and I'm getting this warning
"Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in E:\XAMPP\htdocs\loginapp\login.php on line 8"

Which is strange because my first parameter is indeed a result...

Here's my code

<?php
require "init.php";
$Username= $GET["Username"];
$Passwrd= $
GET["Passwrd"];
$sql= "SELECT Name FROM login WHERE Username = '$Username' AND Passwrd = '$Passwrd'";
$result= mysqli_query($con, $sql);

if(!mysqli_num_rows($result)>0)
{

$status= "failed to connect";
echo json_encode(array("response"=>$status));

}

else
{

$row= mysqli_fetch_assoc($result);
$Name= $row['Name'];
$status= "connected";
echo json_encode(array("response"=>$status, "Name"=>$Name));

}
mysqli_close($con);

?>

    When connecting to a database or querying one, you must always check for errors. You try to use your query results before checking to see if the query worked. According to the docs, mysqli_query returns FALSE on failure. You should check for an empty value before trying to use the result:

    $result= mysqli_query($con, $sql);
    if (!$result) {
      die("Error: \n" . mysqli_error($con));
    }

      This usually means that your mysqli_query() failed for some reason and therefore returned false; so you need to add some error_checking and maybe log some debug info.

      $result = mysqli_query($con, $sql);
      if($result == false) {
        error_log(mysqli_error($con));
        die("DB error, debug info logged");
      }

      (I'm going to guess that you spelled the name of the Password column wrong?)

      For your next lesson, you do not want to use user-supplied data directly in your SQL. Do some Googling on SQL injection to learn more, and see http://www.php.net/manual/en/mysqli.real-escape-string.php .

      PS: Heh...the sneaky imp beat me by a minute.

      NogDog PS: Heh...the sneaky imp beat me by a minute.

      Yes but I forgot to mention SQL injection -- also my code outputs the error to the user, which is not good practice. If someone is attempting SQL injection, the last thing you want to do is show them the error with their attempt. womp womp.

        To add error handling for all the database statements (connection, query, prepare, execute), without having to add program logic at each statement, just use exceptions for errors and let php catch the exception, where it will use its error_reporting, display_errors, and log_errors settings to control what happens with the actual error information. To use exceptions for the php mysqli extension, add the following line of code before you make the database connection -

        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        

        By just changing the php error settings, you can display the database errors when learning, developing, and debugging code/queries, or log the database errors when on a live/public server.

          Write a Reply...