简体   繁体   中英

Having trouble fetching results from a MySQL table with PDO

I'm building a simple login system. What I'm having trouble with is fetching the password hash from the database.

This is what I have:

$statement = 'SELECT Pass FROM Emails WHERE Email = "?"';
$question = array($email);
    try {
        $DB->beginTransaction();
        $preparedStatement = $DB->prepare($statement);
        $preparedStatement->execute($question);
        $resultArr = $preparedStatement->fetchAll();
        print_r($resultArr);
        $DB->commit();
    } catch(\PDOException $ex) {
        echo "Seriously bad error. ";
        echo $ex->getMessage();
        return false;
    }

My problem is that $resultArr always contains no elements.

I know the SQL query itself works, as I've tested it directly in MySQL.

I believe that I have to use a prepared statement, as I'm sending user input to MySQL and have to defend against easy SQL injection attacks.

I'm using fetchAll() in order to make sure that there's only one result for a given email. Otherwise, there will be a huge problem.

What is my mistake here?

Just for sake of cleaning this extremely superfluous code

$stmt = $DB->prepare('SELECT Pass FROM Emails WHERE Email = ?');
$stmt->execute(array($email));
$pass = $stmt->fetchColumn();

these 3 lines is ALL you need to run a query and get result.

And yes, the problem is just quotes around ? mark.

To ensure there is no other email you ought to use unique index in Mysql

$query = 'SELECT Pass FROM Emails WHERE Email = :email';
    try {
        $DB->beginTransaction();
        $preparedStatement = $DB->prepare($query);
        $preparedStatement->bindParam("email", $email, PDO::PARAM_STR);
        $preparedStatement->execute();
        $resultArr = $preparedStatement->fetchAll();
        print_r($resultArr);
        $DB->commit();
    } catch(\PDOException $ex) {
        echo "Seriously bad error. ";
        echo $ex->getMessage();
        return false;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM