PDO basics, but I really don't understand :-(

56 Views Asked by At

I'm really new to PDO, and I can't get this to work :

I want to check a captcha code. Every day, the asked code changes according to the day number. In my database, a table contains two columns: JOUR (=day) and REPONSE (=answer). The user inputs a code I store in $code_entre. This code has to be compared to the input one.

With the date() method, I get the day's number. I store it in $numero_jour. My code is supposed to get the code of the day and compare it to the input one. Here's the code :

            $numero_jour = date(j); //Récupère le numéro du jour en cours.

            $sql2 = $bdd1->prepare('SELECT JOUR FROM questions_securite WHERE REPONSE=:reponse LIMIT 1');

            $sql2->bindParam(':reponse', $code_entre, PDO::PARAM_STR);          
            $sql2->execute();
            $req2 = $sql2->fetch();

            $sql2->closeCursor(); 

            if($req2 != $numero_jour) {
                return 'Erreur de code de sécurité. Veuillez recommencer.';
            }

... and nothing happens ! I tried the "echo $req2 instruction, and all I get is the "Array" word.

What am I doing wrong ? I'm sure the solution is easy, but I don't find it out !

Thanks !

1

There are 1 best solutions below

1
Jonast92 On

Let's take a look at the documentation for PDO's fetch method:

Fetches the next row from a result set

What this means is that $req2 will not be a string but a row containing key->value pairs where the keys represent the columns in the row.

What this essentially means is you need to access the value of the columns within the row.

A given example in the documentation should help you in understanding how to achieve your goal:

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->name;

In this case $result looks like, for example:

Array
(
    [name] => apple
    [colour] => red
)

It's been a while since I used PDO but one example I used at some point to iterate through many rows to fetch the value for a certain column for each row was like this, to help you if you need to check for multiple rows:

...

$sth ->execute();
$sth ->setFetchMode(PDO::FETCH_ASSOC);
$currentName = "";
while ($row = $sth ->fetch())
{
    $currentName = $row['name'];
}

This should be enough to get you started. Remember to use the documentations and highly rated tutorials to help you.