Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding params for PDO statement inside a loop

I'm trying to bind parametres for SQL query inside a loop:

$db = new PDO('mysql:dbname=test;host=localhost', 'test', '');   $stmt = $db->prepare('INSERT INTO entries VALUES (NULL, ?, ?, ?, NULL)');  $title = 'some titile'; $post = 'some text'; $date = '2010-whatever';    $reindex = array(1 => $title, $post, $date); // indexed with 1 for bindParam  foreach ($reindex as $key => $value) {       $stmt->bindParam($key, $value);       echo "$key</br>$value</br>";  //will output: 1</br>some titile</br>2</br>some text</br>3</br>2010-whatever</br> } 

The code above inserts in database in all 3 fields 2010-whatever.

This one works fine:

$stmt->bindParam(1, $title); $stmt->bindParam(2, $post); $stmt->bindParam(3, $date); 

So, my question is why the code in the foreach-loop fails and inserts wrong data in the fields?

like image 744
Buddy Avatar asked Nov 13 '10 20:11

Buddy


People also ask

How do you bind values in PDO?

The PDOStatement::bindValue() function is an inbuilt function in PHP that is used to bind a value to a parameter. This function binds a value to the corresponding named or question mark placeholder in the SQL which is used to prepare the statement.

What is parameter binding in PHP?

bindParam is a PHP inbuilt function used to bind a parameter to the specified variable name in a sql statement for access the database record. bindValue, on the other hand, is again a PHP inbuilt function used to bind the value of parameter to the specified variable name in sql statement.

What does the prepare method of a PDO object return when called successfully?

Return Values ¶ If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns false or emits PDOException (depending on error handling).

What is execute() php?

Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values.


1 Answers

The problem is that bindParam requires a reference. It binds the variable to the statement, not the value. Since the variable in a foreach loop is unset at the end of each iteration, you can't use the code in the question.

You can do the following, using a reference in the foreach:

foreach ($reindex as $key => &$value) {  //pass $value as a reference to the array item     $stmt->bindParam($key, $value);  // bind the variable to the statement } 

Or you could do this, using bindValue:

foreach ($reindex as $key => $value) {     $stmt->bindValue($key, $value);  // bind the value to the statement } 
like image 194
lonesomeday Avatar answered Oct 13 '22 08:10

lonesomeday