Login PHP and MySql generating error mysqli_fetch_array ()

2

Good morning!

I have the following code to log in to the system:

<?php


require_once('conexao.php');

// FETCH DATA FROM FORM USING METHOD POST
// IF BUTTON NAME "LOGIN" IS SET
if (isset($_POST['login'])) {




// FETCH DATA FROM INPUT FIELD
$user = mysqli_real_escape_string($conexao, $_POST['usuario']);
$pass = mysqli_real_escape_string($conexao, $_POST['password']);

  // CHECK ALL FIELD HAS BEEN FILLED UP
 if ($user && $pass) {

   // QUERY FROM DATABASE
  $query= mysqli_query($conexao, "SELECT * FROM usuarios WHERE usuario='".$user."'");
  $checkuser= mysqli_num_rows($query);

   // CHECK IF USERNAME EXIST ON DATABASE
  if($checkuser != 1) {

    // I'LL BE SETTING A VARIABLE IF YOUR DOESN'T EXIST
   $error = "Username doesn't exist in our database!";
  }

   // FETCHING PASSWORD IN DATABASE WHERE USERNAME COINCIDES
  while ($row = mysqli_fetch_array($user)) {
   $checkpass= $row['senha'];


    // CHECK IF ENTERED PASSWORD MEETS THE USERNAME PASSWORD
   if ($pass== $checkpass) {

     // IF ALL OKAY SET SESSION
    setcookie("usuario", $user, time()+7200);
    $_SESSION['usuario'] = $user;
    $_SESSION['start'] = time();
    $_SESSION['expire'] = $_SESSION['start'] + (60 * 60 * 60);
    header("Location: ../admin.php");
    exit();
   } else {

     // SET VARIABLE THAT'LL SHOW IF USER PASSWORD IS INCORRECT
    $error = "Incorrect password!";
   }
  }
 } else {

  // SET VARIABLE IF ALL FIELD ARE NOT FILLED UP
 $error = "Please enter a username and password.";
 }
}


?>

When trying to login, in the "login.php" page, I get the following error:

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, string given in C:\xampp\htdocs\projetoqa\php\checklogin.php on line 32
    
asked by anonymous 01.09.2015 / 16:21

2 answers

2

Try this:

while ($row = mysqli_fetch_array($query))

The first parameter of mysqli_fetch_array() should be resulttype and not a string , which is the variable $user .

In your logic, put everything that comes after checking the user inside a else :

if($checkuser != 1) {
    // I'LL BE SETTING A VARIABLE IF YOUR DOESN'T EXIST
    $error = "Username doesn't exist in our database!";
}
else {
    $row = mysqli_fetch_array($query);
        ....

Otherwise this code will run when the user is not found and may result in an error. And since your query should return only one record, while is not required.

    
01.09.2015 / 16:26
1

You need to pass $ query to mysqli_fetch_array instead of passing the variable $ user.

    
01.09.2015 / 16:26