如何在for循环内将多行数据插入数据库表

时间:2019-07-15 22:47:04

标签: php

如何在for循环内将多行数据插入数据库表中。

示例:我需要运行以下for循环7次,以将DAYS名称插入数据库。

for ($t = 0 ; $t < 7; $t++){
    $defaultValues = "INSERT INTO workingDays (businessID, day, workingHours) VALUES (?,?,?)";
    $pdo->prepare($defaultValues)->execute([$businessID, $dayNames, $hours]);
}

最后,workingDays表应如下所示:

BusinessID: 1, Day: Monday, workingHours: 8
BusinessID: 1, Day: Tuesday, workingHours: 8
BusinessID: 1, Day: Wednesday, workingHours: 8
BusinessID: 1, Day: Thursday, workingHours: 8
BusinessID: 1, Day: Friday, workingHours: 8
BusinessID: 1, Day: Saturday, workingHours: 8
BusinessID: 1, Day: Sunday, workingHours: 8

1 个答案:

答案 0 :(得分:0)

遍历一系列日期名称。

$defaultValues = "INSERT INTO workingDays (businessID, day, workingHours) VALUES (?,?,?)";
$stmt = $pdo->prepare($defaultValues);
$daynames = ['Monday', 'Tuesday', ..., 'Sunday'];
foreach ($daynames as $day) {
    $stmt->execute([$businessID, $day, $hours]);
}