mysqli num_rows expects parameter 1 to be mysqli_result

1

Hello, I'm a beginner in PHP and MySQL and I'm in need of help.

I'm getting the error that is in the question title in my login function:

    public function login ($login, $senha) {
    $result = $this->conn->prepare ("SELECT * FROM usuario WHERE login='$login' and senha='$senha';");
    if(!$result->execute()){
        echo 'erro: '. $result->error;
    }
    if (mysqli_num_rows($result)<=0){
        echo "<script language='javascript' type='text/javascript'>alert('Login e/ou senha incorretos');window.location.href='Teste.php';</script>";
    }else{
        setcookie("login", $login);
        header("Location:index.php");
    }

}

The variable $ result is only receiving value 0 and I am not able to solve it, if someone can help me solve it, I am grateful already.

    
asked by anonymous 30.08.2018 / 16:23

1 answer

1

You have to run store_result and preferably if you use OOP then use everything like this, you do not have to in the mysqli API mix procedural with OOP (I only speak of this API, the rest of PHP is a matter of taste and need, there you can "mix"):

if ($stmt = $mysqli->prepare("SELECT * FROM usuario WHERE login='$login' and senha='$senha';")) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    if ($stmt->num_rows < 1) {
        echo "<script language='javascript' type='text/javascript'>alert('Login e/ou senha incorretos');window.location.href='Teste.php';</script>";
    } else {
        setcookie("login", $login);
        header("Location:index.php");
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();

Another very important thing, why use variables with prepare directly in the string? (no need to respond)

If you want to prevent someone from passing a login or password value that causes a syntax error or even a sql-injetcion directly use bind_param , because that is the goal of prepare , like this:

if ($stmt = $mysqli->prepare("SELECT * FROM usuario WHERE login=? and senha=?")) {

    /* passa os valores na ordem dos interrogações */
    $stmt->bind_param('ss', $login, $senha);

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    if ($stmt->num_rows < 1) {
        echo "<script language='javascript' type='text/javascript'>alert('Login e/ou senha incorretos');window.location.href='Teste.php';</script>";
    } else {
        setcookie("login", $login);
        header("Location:index.php");
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
    
30.08.2018 / 16:49