简体   繁体   中英

PHP PDO Basic prepared statement

I'm trying to do a basic prepared statement using pdo+mysql .. I can't seem to get the values assigned for the life of me :/

 $dbh = new PDO('mysql:dbname=users;host=127.0.0.1', 'localAPI', 'localAPI');
 $a = 'asdf';
 $sth = $dbh->prepare("INSERT INTO users (userName, userPass, accountStatus) VALUES (':a', ':userPass', 'unconfirmed')");
 $sth->bindParam(':a', $a, PDO::PARAM_STR);
 $sth->execute();

Any ideas? Thanks in advance!!

Table results:

mysql> select * from users;
+--------+----------+-----------+---------------+-------------+---------+---------------------+----------+------------+---------+------+
| userId | userName | userPass  | accountStatus | accountType | balance | tCreated            | tUpdated | tLastLogin | promoId | ref  |
+--------+----------+-----------+---------------+-------------+---------+---------------------+----------+------------+---------+------+
|      1 | :a       | :userPass | unconfirmed   | user        |       0 | 2010-12-12 13:42:10 |     NULL |       NULL |    NULL | NULL | 
+--------+----------+-----------+---------------+-------------+---------+---------------------+----------+------------+---------+------+

You are surrounding your variables in the SQL statement with quotes ... ':a' .. . Remove them, as the parser would think you meant a string here, not a variable. You tell the Database that you mean a string with the bind() call.

The var_dump shouldn't show you a query with :test substituted with 123 , which seems to be what you expect. Call $sth->execute(); and you're done.

The reason has to do with how prepared statements work. See, when a query is executed, what happens is that the query is sent as a string to the database. Here it is parsed into an internal form, which is then executed in an interpreter. With a prepared statement, the values of variables (Such as 123 for :test ) is transmitted and parsed separately from the query. This means that you can't "fool" the parser - which is what injection type attacks relies on - simply because the values never are part of the query and thus never reach the parser.

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