Jeff
Jeff

Reputation: 2068

Select query returning only 1 of 2 requested columns

I'm 90% sure the problem is in the sql syntax, but can't seem to spot where exactly. The sql is returning the correct email, however the password returns empty. I have tried using a different column in the database but I get the same problem.

Note: The password is hashed in db.

Code:

$sql = $link->prepare('SELECT email, password FROM users WHERE email=:email');
$sql->bindParam(':email', $email);
$sql->execute();
$resultemail = $sql->fetchColumn();
$resultpassword = $sql->fetchColumn(1);
if (!$resultemail){
    echo "empty";
} else {
    echo $resultemail;
}
if (!$resultpassword){
    echo "empty";
} else {
    echo "$resultpassword";
}

Upvotes: 0

Views: 37

Answers (1)

Barmar
Barmar

Reputation: 781059

Each time you call fetchColumn, it moves to the next row of the result set, and fetches the specified column from that row (the default is column 0). So you're setting $resultemail to the first column of the first row of the results, and $resultpassword to the first column of the second row of the results. But since the query only returns one row, you're setting $resultpassword to false.

You should fetch the whole row, and set the variables to the corresponding columns of that row.

$row = $sql->fetch(PDO::FETCH_ASSOC);
if ($row) {
    $resultemail = $row['email'];
    $resultpassword = $row['password'];
    if (!$resultemail){
        echo "empty";
    } else {
        echo $resultemail;
    }
    if (!$resultpassword){
        echo "empty";
    } else {
        echo "$resultpassword";
    }
} else {
    echo "empty";
}

Upvotes: 2

Related Questions