【问题标题】:How to combine three arrays and insert multiple rows如何组合三个数组并插入多行
【发布时间】:2020-03-05 10:30:14
【问题描述】:

我有 3 个数组,我想要实现的是,使用 foreach 循环,我想在数据库中插入多行。 这是我正在尝试的代码。

$array1 = ('Hello First row', 'Hello Second Row', 'Hello third row', 'Hello Forth row');
$array2 = ('This going to be First row', 'This going to be Second Row', 'This going to bethird row', 'This going to beForth row');
$array3 = ('also the first row', 'also the Second Row', 'also the third row', 'also the Forth row');
$stmt = $db->prepare("INSERT INTO table_name(first, second, third) VALUES (:first, :second, :third)");
$stmt->execute(array(':first' => $array1, ':second' => $array2, ':third' => $array3));

PS:我尝试在 $stmt 执行函数上方使用 foreach 循环,但这并没有按预期工作。!它在表中创建了 12 行。假设只有 4 个。

【问题讨论】:

    标签: php mysql pdo


    【解决方案1】:
    $array1 = ('Hello First row', 'Hello Second Row', 'Hello third row', 'Hello Forth row');
    $array2 = ('This going to be First row', 'This going to be Second Row', 'This going to bethird row', 'This going to beForth row');
    $array3 = ('also the first row', 'also the Second Row', 'also the third row', 'also the Forth row');
    $stmt = $db->prepare("INSERT INTO table_name(first, second, third) VALUES (:first, :second, :third)");
    
    for($index=0; $index<count($array1); $index++) {
        $stmt->execute(array(':first' => $array1[$index], ':second' => $array2[$index], ':third' => $array3[$index]));
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多