The error tells me that it is in the conditional line if
, in which it says if($result->num_rows> 0)
and I don't understand why. My code is the following:
<?php
require_once("sesion.class.php");
$sesion = new sesion();
if( isset($_POST["iniciar"]) )
{
$usuario = $_POST["usuario"];
$password = $_POST["password"];
if(validarUsuario($usuario,$password) == true)
{
$sesion->set("usuarioactual",$usuario);
header("location: index.php");
}
else
{
}
}
function validarUsuario($usuario, $password)
{
$conexion = new mysqli("localhost","root","","cliente");
$consulta = "select clave from usuarios where usuario = '$usuario';";
$result = $conexion->query($consulta);
if($result->num_rows> 0){
$fila = $result->fetch_assoc();
if( strcmp($password,$fila["clave"]) == 0 )
return true;
else
return false;
}
else
return false;
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>login in</title>
</head>
<body>
<div class="wrapper fadeInDown">
<div id="formContent">
<h2>Log in</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="usuario" placeholder="Usuario">
<input type="password" name="password" placeholder="Password">
<button class="fadeIn fourth" name="iniciar">Iniciar</button>
</form>
</div>
</div>
</body>
</html>
It may
$result
befalse
because the query failed. That is why you should not go on to read resources without first verifying them.You are making the typical error of what I call naive or optimistic programming , that is, programming thinking that errors or problems do not exist and therefore not facing them.
You should check everything that can fail:
If you want to know what happened, for example to display custom error messages, you can do so, using the respective ones
else
for each blockif
. I've omitted it here, because according to the logic of the code, it should returnfalse
when something has failed or doesn't validate.Safety Note
Your current code is highly vulnerable to SQL injection attacks . Consider using prepared queries to neutralize that serious security hazard.