[英]How can I insert multiple values using a loop?
这是我的代码:
$post_id = 10;
$tags_id = [23, 55, 155, 15];
$stmt = $dbh_conn->prepare("INSERT INTO post_tags (post_id, tag_id) VALUES (?, ?)");
$stmt->execute([$post_id, $tags_id[0]]);
if ( !$stmt->rowCount() ){
throwErrorMessage("Something went wrong while inserting tags");
}
如您所见,我的代码仅插入一行。 我可以计算count($tags_id)
的数量,然后根据该数量复制粘贴整个代码。 但是这种方法对我来说似乎并不好。 知道使用循环的最佳方法是什么吗?
准备一次并插入循环:
$stmt = $dbh_conn->prepare("INSERT INTO post_tags (post_id, tag_id) VALUES (?, ?)");
foreach ($tags_id as $tag) {
$stmt->execute([$post_id, $tag]);
if ( !$stmt->rowCount() ){
throwErrorMessage("Something went wrong while inserting tag " . $tag);
}
}
您可以…
A)使用单个语句并在循环中生成VALUES (…)
部分。
$values = [];
foreach ($tags_id as $tag) {
$values[] = sprintf( '(%d, %s)', (int)$post_id, $dbh_conn->quote($tag) );
}
$stmt = $dbh_conn->prepare(
sprintf(
'INSERT INTO post_tags (post_id, tag_id) VALUES %s;',
implode(',', $values)
));
if(!$stmt->execute()) {
// something went wrong
}
要么
B)对每个INSERT
语句重复使用一行,并在循环内调用execute。 (如其他答案所建议)
准备插入查询并执行一次。 尝试下面的代码,可能会有所帮助
$post_id = 10;
$tags_id = [23, 55, 155, 15];
$lastElement = end($tags_id);
$insert = "INSERT INTO post_tags (post_id, tag_id) VALUES";
foreach ($tags_id as $key => $value)
{
if ($value == $lastElement) {
$insert .= "(".$post_id.", ".$value.")";
} else {
$insert .= "(".$post_id.", ".$value."),";
}
}
$stmt = $dbh_conn->prepare($insert);
$stmt->execute();
if ( !$stmt->rowCount() ){
throwErrorMessage("Something went wrong while inserting tags");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.