douyue6520 2012-08-26 14:25
浏览 81
已采纳

多个MySQL行INSERT失败

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?

  • 写回答

3条回答 默认 最新

  • dongtiaozhou4914 2012-08-26 14:45
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答