I was doing a simple INSERT
during my development, but I'm going back and putting in SQL protection and prepared statements. The error I receive is:
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Here is the code that I'm using from help from others on SO.
// foreach to set up variables
foreach ($json as $text) {
$uoid = mysql_real_escape_string($uoid);
$filename = mysql_real_escape_string($uoid.".jpg");
$filedate = mysql_real_escape_string($datetime);
$imagedesc = mysql_real_escape_string($desc);
// array of values
$insert[] = array($uoid,$filename,$filedate,$imagedesc);
}
function placeholders($text, $count=0, $separator=","){
$result = array();
if($count > 0){
for($x=0; $x<$count; $x++){
$result[] = $text;
}
}
return implode($separator, $result);
}
foreach($insert as $d){
$question_marks[] = '(' . placeholders('?', sizeof($d)) . ')';
}
$pdo = new PDO('mysql:dbname=photo_gallery;host=127.0.0.1', 'myuser', 'mypass');
$pdo->beginTransaction();
$sql = "INSERT INTO wp_gallery (" . implode(',', array_values($insert) ) . ")
VALUES " . implode(',', $question_marks);
// reading output
echo $sql;
$stmt = $pdo->prepare($sql);
try {
$stmt->execute($insert[0]);
} catch (PDOException $e){
echo $e->getMessage();
}
$pdo->commit();
When I look at the SQL output:
INSERT INTO wp_gallery (10219776,10219776.jpg,my image description,2012-08-01 15:36:29)
VALUES (?,?,?,?),(?,?,?,?),(?,?,?,?),(?,?,?,?)
Everything matches just by the look of it, but I'm still baffled as to how to fix this. Can someone point out what I'm doing wrong?