如何使用循环插入多个值?

时间:2018-04-11 08:03:22

标签: php mysql sql loops

这是我的代码:

$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)的数量,并根据该数字复制粘贴整个代码。但这种方法对我来说似乎并不好。知道什么是使用循环的最佳方法吗?

3 个答案:

答案 0 :(得分:4)

准备一次并插入循环:

$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);
    }
}

答案 1 :(得分:2)

你可以......

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。 (如其他答案所示)

答案 2 :(得分:0)

准备插入查询并执行一次。试试下面的代码,可能会有所帮助

$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");
}