PDO如何进行此查询?

时间:2013-08-22 10:24:49

标签: php sql pdo phpmyadmin

$what = "(999,'string','string2'),(21,'aaaa','bbbbb'),(22,'ccccc','ddddd')";
include("../connect/pdoconnect.php");
try {

$sql = $db->prepare("INSERT INTO `bd_fortest` (`user_ID`, `picturename`, `picturepath`) VALUE :what");
$sql->execute(array(":what"=>$what));


}
catch(PDOException $e) {  
    echo "\nPDO::errorInfo():\n";
    print_r($db->errorInfo());
}

$ get-data-from-csv-function的值是什么,所以我们不知道它有多少。 我自己尝试,PDO不能做这个查询。我该怎么办?

1 个答案:

答案 0 :(得分:3)

您不能使用单个占位符执行此操作。只有在允许普通表达式的情况下才允许占位符,并且值列表不是单个表达式。

所以你需要使用字符串插值/连接,如Gautam3164的答案,或者使用一次插入一行的循环,例如

$whats = array(array('userid' => 999, 'picturename' => 'string', 'picturepath' => 'string2'),
               array('userid' => 21, 'picturename' => 'aaaa', 'picturepath' => 'bbbbb'),
               array('userid' => 22, 'picturename' => 'ccccc', 'picturepath' => 'ddddd')
              );
$sql = $db->prepare("INSERT INTO `bd_fortest` (`user_ID`, `picturename`, `picturepath`) VALUES (:userid, :picturename, :picturepath)");
foreach ($whats as $what) {
    $sql->execute($what);
}

如果使用字符串连接,则会失去对参数化语句的保护。您需要确保所有字符串都已正确清理或转义。