davemib123
davemib123

Reputation: 135

PDO fetch vs rowcount

I’m having a practice in creating a login script in PHP using PDO, but have run into a slight problem. I’ve got it to check if data is in the fields, but unsure of how to check if the username and password combination is correct. This is a snippet of checking the username and password:

# if data is valid, check against values held in the database
if ($valid) {
    $sql = 'SELECT COUNT(*) FROM authors
    WHERE email = :email AND password = :password';
    
    $s = $dbConnection->prepare($sql);
    $s->bindValue(':email', $email);
    $s->bindValue(':password', $password);
    $s->execute();
    
    $row = $s->fetch();
    
    if($row==1){
        echo "ok";
    }else{
        echo "no";
    }
}

When I put in any combination for username and password I get the output for false (i.e. echo ‘no’). Could someone give me a hand please?


UPDATE: Snippet modified

I've used password_verify, but I still have the same result:

// if data is valid, check against values held in the database
if ($valid) {
    $sql = 'SELECT * FROM author
    WHERE email = :email';
    
    $s = $dbConnection->prepare($sql);
    $s->bindValue(':email', $email);
    $s->execute();
    
    $row = $s->fetch();
    var_dump($row);

    if(count($row) > 0 && password_verify($password, $row['password'])){
        echo 'ok';
        exit;
    }else {
        echo 'Username and Password are not found';
    }
}

var_dump of incorrect data:

bool(false) Username and Password are not found

var_dump of correct data:

array(4) { ["id"]=> string(1) "3" ["name"]=> string(7) "[email protected]" ["email"]=> string(7) "[email protected]" ["password"]=> string(1) "a" } Username and Password are not found

Upvotes: 0

Views: 128

Answers (1)

davemib123
davemib123

Reputation: 135

got it sorted. solution i used was:

# if data is valid, check against values held in the database and then action as appropriate
if ($valid) {
    $sql = 'SELECT id, email, password FROM author
    WHERE email = :email AND password = :password';

    $s = $dbConnection->prepare($sql);
    $s->bindValue(':email', $email);
    $s->bindValue(':password', $password);
    $s->execute();

    $data = $s->fetch();
    if($data != NULL){
        $_SESSION['loggedIn'] = TRUE;
        $_SESSION['email'] = $email;
        $_SESSION['id'] = $data['id'];
        header('Location:../admin/');
        exit;
    }else{
        unset($_SESSION['loggedIn']);
        unset($_SESSION['email']);
        unset($_SESSION['id']);
        echo 'Incorrect username/password combination';
    }
}

Upvotes: 0

Related Questions