php - Mysqli to PDO conversion

591

I recently started using PDO a few days ago and am changing all my mysqli code but I seem to have hit a brick wall. Now this code worked beautifully when I was using mysqli, but now I can't seem to print out the result. This code basically takes the input value of password, and that of the hashed password in the database, matches them and if both are equal then the user will be logged in. My problem is that I can't seem to find a way to get the password from my database. Any help would be much appreciated. Thank you.

<?php 
 session_start();

 $user = "root";
 $pass = "";

$mcon = new PDO('mysql:host=localhost;dbname=rabbit_users', $user, $pass);

 try {
 $mcon = new PDO('mysql:host=localhost;dbname=rabbit_users', $user, $pass);
$mcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();



//prepare statement
$password = $_POST['password']; 

$stmt = $mcon->prepare("SELECT `password` FROM members WHERE password=:password");
$stmt->bindParam(":password", $_POST['password']);
$stmt->execute();

//get_result
$data_array = $stmt->fetchAll();
$stmt->fetch(PDO::FETCH_ASSOC);

//echo passwords
print 'Password from form: ' . $password . '<br />';
print 'Password from DB: ' . $data_array['password'] . '<br />';

//verify password
if (password_verify($password, $data_array['password'])) {
    print 'success';
    exit();
}else{
    print 'Try again m9';
    exit();
}
305

Answer

Solution:

fetchAll returns an array containing all of the result set rows. So you can access topassword with$data_array[0]['password'] if you used it. You may want use fetch instead.

$data_array = $stmt->fetch(PDO::FETCH_ASSOC);

People are also looking for solutions to the problem: PHP: do this || that (like javascript)

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.