TaneMahuta
TaneMahuta

Reputation: 367

PHP / MySQL: How to compare selected value with input received via $_POST

I am new to MySQL and have a simple question:

I am building a page where users need to login to a site and when they login I want to check:

  1. if their email is already in the db and
  2. if the password they entered matches the registered one.

So far I have the following which should cover the first part but I am not sure how I can refer to the password that I selected from the db so that I can set up an if / else then for the comparison.

Can someone help me with this ?
Also, if there is a better way to approach this please let me know as well.

My SQL:

$conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName);
$conn->set_charset("utf8");
if($conn->connect_error){
    die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$pw = password_hash($_POST["pw"], PASSWORD_BCRYPT); 

$stmt = $conn->prepare("SELECT email, pw FROM Users WHERE email = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
if(mysqli_num_rows($result) = 0){
    echo "Email has not been registered yet";
}else{
    if(
        // compare pw with $pw
    }
}
$conn->close();

Many thanks in advance.

Upvotes: 0

Views: 788

Answers (2)

dajnz
dajnz

Reputation: 1188

Your $result var in instance of mysqli_result class, so use it's method fetch_assoc() (as Michael Berkowski said) to get assoc array with keys 'email' and 'pw', according to your sql. Then you can easily check if your password matches with hash from your db, using password_verify($pass, $hash) -> bool, as other answer already said.

Upvotes: 1

Clyde Winux
Clyde Winux

Reputation: 295

Try this one:

$conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$pw = password_hash($_POST["pw"], PASSWORD_BCRYPT); 

$stmt = $conn->prepare("SELECT email, pw FROM Users WHERE email = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
if(mysqli_num_rows($result) = 0){
echo "Email has not been registered yet";
}else{
if($pw===$result['pw']){
   //password matched
  }
else { //password wrong
}

}
}
$conn->close();

Upvotes: 1

Related Questions