简体   繁体   English

使用PDO在mysql表中插入多个值

[英]inserting multiple values in mysql table using PDO

I have a form that submits check boxes to a PHP PDO script. 我有一个表单,可以将复选框提交到PHP PDO脚本。 I have code that is as follows to store the values into a mysql table 我有如下代码将值存储到mysql表中

$stmt = $dbPDO->prepare("INSERT INTO group_members(g_id, em_id) 
                         VALUES(:g_id,:em_id) 
                         ON DUPLICATE KEY UPDATE g_id = :g_id,  em_id = :em_id");
foreach ($_POST['id'] as $email) {
  $stmt->bindParam(':g_id', $gid , PDO::PARAM_INT);
  $stmt->bindParam(':em_id', $email , PDO::PARAM_STR);
  $stmt->execute();
}

PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number' PHP致命错误:消息为“ SQLSTATE [HY093]:参数号无效”的未捕获异常“ PDOException”

This generates an error. 这会产生一个错误。 What is the best way to insert multiple values into a mysql table with different values? 将多个值插入具有不同值的mysql表中的最佳方法是什么?

Every named placeholder have to be unique! 每个命名的占位符必须是唯一的!

$stmt = $dbPDO->prepare("INSERT INTO group_members(g_id, em_id) VALUES(:g_id,:em_id) ON DUPLICATE KEY UPDATE g_id = :g_id2,  em_id = :em_id2");

$email=null;
//just bind once, that the logic behind 'bind()'
$stmt->bindParam(':g_id', $gid , PDO::PARAM_INT);
$stmt->bindParam(':em_id', $email , PDO::PARAM_STR);
$stmt->bindParam(':g_id2', $gid , PDO::PARAM_INT);
$stmt->bindParam(':em_id2', $email , PDO::PARAM_STR);

foreach ($_POST['id'] as $email) {
    $stmt->execute();//write your rows
}
$stmt->close();

You can't reuse placeholder names. 您不能重复使用占位符名称。 You have to create new ones, or use VALUES in your update portion: 您必须创建新的,或在更新部分中使用VALUES:

$stmt = $dbPDO->prepare("INSERT INTO group_members(g_id, em_id) VALUES(:g_id,:em_id) ON DUPLICATE KEY UPDATE g_id = VALUES(g_id),  em_id = VALUES(em_id)");

You can't reuse a placeholder unless you have emulation mode turned on. 除非打开了仿真模式,否则您不能重复使用占位符。

Generally speaking, PDO_MYSQL should have emulation on by default. 一般来说,默认情况下,PDO_MYSQL应该启用仿真。 The reason being that MySQL performs poorly with prepared statements. 原因是MySQL在准备好的语句上执行不佳。 Emulation works significantly faster. 仿真的工作速度明显加快。

That said, if it is not on for whatever reason, you can set it manually using: 就是说,如果由于某种原因未打开,则可以使用以下命令手动进行设置:

$dbc->setAttribute(PDO::ATTR_EMULATE_PREPARES,true);

In fact, if you are not sure, just set it anyway. 实际上,如果不确定,则无论如何都要进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM