gpt4 book ai didi

php - 如何使用php向mysql数据库插入多行,增加1行

转载 作者:行者123 更新时间:2023-11-29 19:10:49 24 4
gpt4 key购买 nike

我想向我的 SQL 数据库添加 30 行。该表有 3 列:“年”、“月”、“日”。这些行应添加到“日”列。我使用以下代码,因为我想执行一次。当我通过 RESTeasy 发布它时,我可以在 PHPmyadmin 中看到仅添加了最后一行,在本例中:“2017”“1”“31”。

// Add days in month
$app->post('/api/calendar/add', function (Request $request, Response $response) {
$year = $request->getParam('Year');
$month = $request->getParam('Month');
$day = $request->getParam('Day');

$day = 1;
while($day < 31) {
$day = $day + 1;
$sql = "INSERT INTO `days` (`Year`, `Month`, `Day`) VALUES ('2017', '1', '$day')";
};

try {
// Get DB Object
$dbcalendar = new dbcalendar();
// Connect
$dbcalendar = $dbcalendar->connect();

$stmt = $dbcalendar->prepare($sql);

$stmt->bindParam(':Year', $year);
$stmt->bindParam('Month', $month);
$stmt->bindParam('Day', $day);

$stmt->execute();

echo '{"notice": {"text": "Days Added"}';

} catch(PDOException $e) {
echo '{"error": {"text": '.$e->getMessage().'}';
}

最佳答案

您需要将try catch移至while

// Add days in month
$app->post('/api/calendar/add', function (Request $request, Response $response) {
$year = $request->getParam('Year');
$month = $request->getParam('Month');
$day = $request->getParam('Day');

$day = 1;
while($day < 31) {
$day = $day + 1;
$sql = "INSERT INTO `days` (`Year`, `Month`, `Day`) VALUES ('2017', '1', '$day')";

try {
// Get DB Object
$dbcalendar = new dbcalendar();
// Connect
$dbcalendar = $dbcalendar->connect();

$stmt = $dbcalendar->prepare($sql);

$stmt->bindParam(':Year', $year);
$stmt->bindParam('Month', $month);
$stmt->bindParam('Day', $day);

$stmt->execute();

echo '{"notice": {"text": "Days Added"}';

} catch(PDOException $e) {
echo '{"error": {"text": '.$e->getMessage().'}';
}
};
});

关于php - 如何使用php向mysql数据库插入多行,增加1行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43096975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com