简体   繁体   中英

Why should I use bindValue / Param vs a normal variable?

I can see many discussions on why is better to use PDO bindValue vs bindValue. But what I could not find was precice information on why should I use that vs a simple variable in the query. Could anyone tell me? thanks

$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindParam(':sex', $sex); 
$s->execute();

VS

$sex = 'male';
$s = $dbh->query('SELECT name FROM students WHERE sex = $sex'); // OR PREPARE, The question is how to pass the variable.

The main reason is by using prepared statements and bound variables you protect yourself against the most common vector used for sql injection attacks.

A second reason is if you have multipe requests to run the same query statement, but with different variable values, you can save time by only having the server calculate the execute plan once, then run it on the the variables as you call the same statement over and over. Think about looping over the same statement several time. This is the concept of serverside prepared statements which mysql allows and PDO supports.

Like others have said, you want to use PDO to prevent SQL injection. Say a user with bad intentions types something like ';drop table students;-- into an input box on your site. Without PDO, the final query will look like this:

SELECT name FROM students WHERE sex = '';drop table students;--'

See what would happen? The select statement would run and not find any results (unless you have students in your table with no sex specified). Then, the drop statement would run, and your entire students table would be deleted.

This is just one example—there are all kinds of SQL injection attacks, many of them more dangerous than this. Using PDO prevents pretty much all of them. Internally, the bound variables are kept separate from the query itself.

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