Checking if the username and password are correct

Like my code right now, I always get echo "Username/Password incorrect.";

if the username / password is the same or not. My question is, what did I do wrong in the below code for php to always repeat "Username / Password wrong"

<?php
require 'privstuff/dbinfo.php';

$password1 = $_POST["password1"];
$username = $_POST["username"];

$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);


if(mysqli_connect_errno()) {
    echo "Connection Failed. Please send an email to owner@othertxt.com regarding this problem.";
    exit();
}

if ($stmt = $mysqli->prepare("SELECT username, password FROM accounts WHERE username=? and password=?")) {

    $db_pw = password_hash($password1, PASSWORD_BCRYPT);

    $stmt->bind_param("ss", $username, $db_pw);
    $stmt->execute();
    if ($stmt->affected_rows > 0) {

        echo "Logged in.";
    }else{
        echo "Username/Password incorrect.";
    }
    $stmt->close();
}
$stmt->close();

$mysqli->close(); 

?>

      

Update . I changed if ($stmt->affected_rows > 0)

to if ($stmt->num_rows)

. Still not working, although UPDATE 2 I figured out the problem is with the use password_hash($password1, PASSWORD_BCRYPT);

. I didn't understand that the hash gives different strings every time. I don't understand how to use password_verify

+3


source to share


2 answers


I understood that. I shouldn't have used password_hash again. I didn't realize that using password_hash gives different results. Then I changed it to use password_verify.



<?php
require 'privstuff/dbinfo.php';


$username = $_POST["username"];
$password1 = $_POST["password1"];

$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);

// Check connection
if(mysqli_connect_errno()) {
    echo "Connection Failed: " . mysqli_connect_errno();
    exit();
}

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT `password` FROM `accounts` WHERE username = ?")) {

    /* Bind parameters: s - string, b - blob, i - int, etc */
    $stmt -> bind_param("s", $username);

    /* Execute it */
    $stmt -> execute();

    /* Bind results */
    $stmt -> bind_result($result);

    /* Fetch the value */
    $stmt -> fetch();

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


if(password_verify($password1, $result))
{
    echo("Hello");
}else{
    echo("No-Go");
}

$mysqli->close(); 
?>

      

0


source


The documentation mysqli_stmt_affected_rows()

says:

This feature only works with queries that update the table. To get the row count from a SELECT query, use mysqli_stmt_num_rows () instead .



You also need to call first mysqli_stmt_store_results()

to buffer the results.

$stmt->store_results();
if ($stmt->num_rows > 0) {
    ...
}

      

+4


source







All Articles