简体   繁体   中英

inserting multiple values in mysql table using PDO

I have a form that submits check boxes to a PHP PDO script. I have code that is as follows to store the values into a mysql table

$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'

This generates an error. What is the best way to insert multiple values into a mysql table with different values?

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:

$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. The reason being that MySQL performs poorly with prepared statements. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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