Ready-made PDO instructions: how to execute, check affected lines, and then retrieve a field

I am very new to PDO, and I was told that this morning he is heading in that direction. So listen to me. I am trying to rewrite my login verification function from standard mysql_query() into a prepared PDO report, but I am encountering some problems.

The loginCheck () function passes the provided letter and password, and then takes the salt from the corresponding letter, if the number of affected lines in this request is 1, apply the $salt variable to the result of this request.

For the last part of the function, I previously just used:

 // standard mysql query goes here if (mysql_num_rows($query) == 1) { $salt = mysql_result($query, 0); } 

Now my whole function looks like this:

 // new mysql query below global $dbh; $stmt = $dbh->prepare("SELECT `salt` FROM `users` WHERE `email`=? LIMIT 1"); $stmt->execute($email); // not sure what to write here? 

but it's hard for me to figure out how to translate the top of the code to something similar in PDO. I also probably do something else wrong here (as always), so point it to me as well.

I looked at the PHP manual and I just don’t understand most of it. Any ideas?

+4
source share
2 answers

I assume you are looking for PDOStatement::rowCount :

 $stmt = $dbh->prepare("SELECT `salt` FROM `users` WHERE `email`=? LIMIT 1"); $stmt->execute($email); if ($stmt->rowCount() == 1) { $salt = $stmt->fetchColumn(0); } 

I would rather write it like this:

 $stmt = $dbh->prepare("SELECT `salt` FROM `users` WHERE `email`= :email LIMIT 1"); $stmt->execute(compact('email')); $user = $stmt->fetch(PDO::FETCH_ASSOC); if ($user) { // work with $user['salt'] } 

Explicit naming is more reliable than depending on the number of columns.


To understand leadership, you need to understand object-oriented notation / concepts. The documentation for the PDO class is as follows:

 PDO { ... PDOStatement prepare ( string $statement [, array $driver_options = array() ] ) ... } 

This means the PDO object ( $dbh in your example) has a prepare method that returns a PDOStatement object. You use it as follows:

 $stmt = $dbh->prepare(...); 

So $stmt is a PDOStatement object. Knowing this, you can look at the documentation for PDOStatement and see that it has an int PDOStatement::rowCount ( void ) method int PDOStatement::rowCount ( void ) that you can use.

+13
source

Here is my favorite PDO tutorial. He answers all your questions:

+2
source

Source: https://habr.com/ru/post/1388081/


All Articles