2010-11-13 20 views
23

que estoy tratando de obligar a los parámetros de consulta SQL dentro de un bucle:params vinculante para la declaración DOP dentro de un bucle

$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> 
} 

El código anterior insertos en la base de datos en los 3 campos 2010-whatever.

Ésta funciona bien:

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

Por lo tanto, mi pregunta es por qué el código en el bucle foreach-falla e inserta datos erróneos en los campos?

Respuesta

41

El problema es que bindParam requiere una referencia. Vincula la variable a la declaración, no el valor. Dado que la variable en un bucle foreach se desactiva al final de cada iteración, no puede usar el código en la pregunta.

Puede hacer lo siguiente, usando una referencia en el 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 
} 

O usted podría hacer esto, usando bindValue:

foreach ($reindex as $key => $value) { 
    $stmt->bindValue($key, $value); // bind the value to the statement 
} 
+0

Hola Ionesomeday - He encontré con un problema similar . ¿Podrías echarme una mano con esto por favor? http://stackoverflow.com/questions/34285341/php-function-procedure-to-bind-question-marks-dynamically – usert4jju7

+0

La pregunta es: ¿cuál es mejor? bindValue o bindParam. –

+1

@IdanMagled Aquí creo que 'bindValue' es más intuitivo. 'bindParam' ofrece ventajas en algunas circunstancias. – lonesomeday

Cuestiones relacionadas