php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #62207 foreaching bindparam results in all params equaling last value
Submitted: 2012-06-01 14:39 UTC Modified: 2012-06-04 23:41 UTC
From: mike dot mackintosh at angrystatic dot com Assigned:
Status: Not a bug Package: PDO related
PHP Version: 5.4.4RC2 OS: Ubuntu 12.04 x86_64
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: mike dot mackintosh at angrystatic dot com
New email:
PHP Version: OS:

 

 [2012-06-01 14:39 UTC] mike dot mackintosh at angrystatic dot com
Description:
------------
I have noticed an issue when working with MySQL and PDO prepare statements. If running a foreach on an array which contains the params for the prepare statement, all params equal the value of the last param in the array. 

See below.

Test script:
---------------
$pdo = new PDO('mysql:dbname=netsec_v2;host=localhost;', 'root', '');
$stmt = $pdo->prepare("CREATE TABLE BugTest 
			(
			ID int NOT NULL AUTO_INCREMENT,
			PRIMARY KEY(ID),
			ColumnA varchar(15) NOT NULL,
			ColumnB int NOT NULL
			)");
$stmt->execute();
		
$array = array(":ColumnA" => "A", ":ColumnB" => 1);
		
$stmt2 = $pdo->prepare("INSERT INTO BugTest (ColumnA,ColumnB) VALUES (:ColumnA, :ColumnB)");

foreach($array as $param => $value){
	$stmt2->bindParam($param, $value);	
}
$stmt2->execute();
		
$res = $pdo->query("SELECT * FROM BugTest")->fetchAll(PDO::FETCH_ASSOC);
var_dump($res);


Expected result:
----------------
ColumnA = A
ColumnB = 1

Actual result:
--------------
ColumnA = 1
ColumnB = 1

Patches

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-06-01 19:49 UTC] mail+php at requinix dot net
Not a bug.

bindParam() works the value by-reference, which means you passed it a reference to the $value variable. Not 
its value at the time you called it. When the loop ends and you call query(), $value will be whatever the 
last one in the $array was: 1.

Use a reference to the item in the array:
  $stmt2->bindParam($param, $array[$param]);
 [2012-06-01 19:51 UTC] mail+php at requinix dot net
Er, when you call execute(), not query().
 [2012-06-04 23:41 UTC] johannes@php.net
-Status: Open +Status: Not a bug
 [2012-06-04 23:41 UTC] johannes@php.net
As said above.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Sep 08 23:01:28 2024 UTC