简体   繁体   中英

insert multiple rows using PDO

What's wrong with this code? i want to insert multiple rows with same movie id and different actor id. when i run this with $actors = array(1,2,3,4); (or any value) and $movid = 1, all the four rows are inserted as values (1, 4).

$create_query = "INSERT INTO `tableName`(`movId`, `actId`) VALUES";
$comma = "";
foreach ($actors as $key=>$value) {
    $create_query .= $comma . "(:movie" . $key . ", :actor" . $key . ")";
    $comma = ", ";
}
$query = $db->prepare($create_query);
foreach ($actors as $key=>$value) {
    echo $movid . ', ' . $value //correct output (1, 1), (1, 2) ...
    $query->bindParam(":movie" . $key, $movid, PDO::PARAM_INT);
    $query->bindParam(":actor" . $key, $value, PDO::PARAM_INT);
}
print_r($query);
//output is
/*INSERT INTO `tableName`(`movId`, `actId`) VALUES(:movie0, :actor0), (:movie1, :actor1), (:movie2, :actor2), (:movie3, :actor3)*/
if ($query->execute()) {
    $return = $query->rowCount();
    $query->closeCursor();
}

when i use separate queries for inserting, it works correctly.

Use PDOStatement::bindValue() instead of PDOStatement::bindParam() . The latter will bind by reference , and since you're using a variable that changes with each loop iteration, you end up trying to bind everything to the same thing.

From the documentation for PDOStatement::bindParam() :

Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

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