PHPPDOStatement: analysis of data insertion errors in bindParam. If you don't talk much about it, simply look at the code: Copy the code as follows :? Php $ dbhnewPDO (mysql: hostlocalhost; dbnametest, test); $ queryQUERYINSERTINTO 'user' ('username', 'passwor doesn't talk much about it. read the code directly:
The code is as follows:
$ Dbh = new PDO ('MySQL: host = localhost; dbname = test', "test ");
$ Query = < Insert into 'user' ('username', 'password') VALUES (: username,: password );
QUERY;
$ Statement = $ dbh-> prepare ($ query );
$ Bind_params = array (': username' => "laruence",': password' => "weibo ");
Foreach ($ bind_params as $ key => $ value ){
$ Statement-> bindParam ($ key, $ value );
}
$ Statement-> execute ();
What are the final SQL statements and the above code?
Okey, I think most of my colleagues think that the final SQL statement is:
Insert into 'user' ('username', 'password') VALUES ("laruence", "weibo ");
However, unfortunately, if you are wrong, the final SQL statement is:
Insert into 'user' ('username', 'password') VALUES ("weibo", "weibo ");
Is it a big pitfall?
This problem comes from today's Bug report: #63281
The reason is the difference between bindParam and bindValue. bindParam requires that the second parameter be a reference variable ).
Let's split the foreach of the above code, that is, the foreach:
The code is as follows:
Foreach ($ bind_params as $ key => $ value ){
$ Statement-> bindParam ($ key, $ value );
}
Equivalent:
The code is as follows:
// The first cycle
$ Value = $ bind_params [": username"];
$ Statement-> bindParam (": username", & $ value); // at this time, username is a reference to the $ value variable.
// The second cycle
$ Value = $ bind_params [": password"]; // oops! $ Value is overwritten with: password value
$ Statement-> bindParam (": password", & $ value );
Therefore, when using bindParam, pay special attention to the trap used in combination with foreach. what is the correct method?
1. do not use foreach, but assign values manually.
The code is as follows:
$ Statement-> bindParam (": username", $ bind_params [": username"]); // $ value is a reference variable
$ Statement-> bindParam (": password", $ bind_params [": password"]);
2. use bindValue instead of bindParam, or directly pass the entire parameter array in execute.
3. use foreach and reference (not recommended)
The code is as follows:
Foreach ($ bind_params as $ key => & $ value) {// note the following:
$ Statement-> bindParam ($ key, $ value );
}
Finally, I will show that when using foreach, we should be cautious when using functions that require parameter reference and delayed processing!
Refer to the code: the code is as follows :? Php $ dbh = new PDO ('MySQL: host = localhost; dbname = test', "test"); $ query = query insert into 'user' ('username ', 'passwor...