-2

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?

4

3 回答 3

0

You're passing values as column names, and you're not passing the correct parameter to execute;

Something like this would be more correct;

// Replace the $insert buildup. Array of values, you don't want an array of arrays here.
$insert = array_merge($insert, array($uoid,$filename,$filedate,$imagedesc));

...

$column_names = array("column1", "column2", "column3", "column4");

$sql = "INSERT INTO wp_gallery (" . implode(',', $column_names ) . ") 
    VALUES " . implode(',', $question_marks);

$stmt->execute($insert);
于 2012-08-26T14:45:33.950 回答
0

INSERT 语句如下所示:

INSERT INTO name_of_the_table (name_of_column_1, name_of_column_2,...) VALUES
 (value_of_column_1, value_of_column_2), (value_of_column_1, value_of_column_2);

如果按照定义的顺序设置所有列的值,则可以省略列的名称。

但是,您将值放在列名应该放在哪里,把问号放在应该放在哪里。

于 2012-08-26T14:32:45.300 回答
0

插入 tbl_name (col1,col2) 值(111,222),(333,444);

于 2012-08-26T14:34:24.143 回答