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 | 开发者_StackOverflow社区 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 i s 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.
精彩评论