gpt4 book ai didi

PHP PDO 将多行/值插入到 mySQL 表中

转载 作者:行者123 更新时间:2023-11-29 12:53:46 26 4
gpt4 key购买 nike

我正在将此表单提交到 mySQL 数据库中的表中。所有行的字段 max 都相同,但每行都有 2 个唯一值。

<form action="file.php" method="post" enctype="multipart/form-data" name="form1" id="form1"> 
<label>Max: </label><input type="number" name="max" value="" autocomplete="off">

<label>Times (hh:mm): </label>
<input type="time" name="time1_1" value="" autocomplete="off"><span> &amp; </span><input type="time" name="time2_1" value="" autocomplete="off">
<input type="time" name="time1_2" value="" autocomplete="off"><span> &amp; </span><input type="time" name="time2_2" value="" autocomplete="off">
<input type="time" name="time1_3" value="" autocomplete="off"><span> &amp; </span><input type="time" name="time2_3" value="" autocomplete="off">
<input type="time" name="time1_4" value="" autocomplete="off"><span> &amp; </span><input type="time" name="time2_4" value="" autocomplete="off">
<input type="time" name="time1_5" value="" autocomplete="off"><span> &amp; </span><input type="time" name="time2_5" value="" autocomplete="off">
<input type="time" name="time1_6" value="" autocomplete="off"><span> &amp; </span><input type="time" name="time2_6" value="" autocomplete="off">
<input type="time" name="time1_7" value="" autocomplete="off"><span> &amp; </span><input type="time" name="time2_7" value="" autocomplete="off">
<input type="time" name="time1_8" value="" autocomplete="off"><span> &amp; </span><input type="time" name="time2_8" value="" autocomplete="off">
<input type="time" name="time1_9" value="" autocomplete="off"><span> &amp; </span><input type="time" name="time2_9" value="" autocomplete="off">
<input type="time" name="time1_10" value="" autocomplete="off"><span> &amp; </span><input type="time" name="time2_10" value="" autocomplete="off">
<button name="submit" type="submit">Submit</button>
</form>

该表包含表单中的所有时间值和最大数量。

    ------------------------------------
| id max time1 time2 |
| 1 25 13:30 19:30 |
| 2 25 14:00 20:00 |
------------------------------------

有没有办法提交所有 20 个时间值(如果不为空),而不是对每个时间值执行以下操作?

    $sql = "INSERT INTO tbl_name (max, time1, time2) VALUES (:max, :time1, :time2)";
$stmt = $db->prepare($sql);
$stmt->execute(array(
":max" => $_POST['max'],
":time1" => $_POST['time1_1'],
":time2" => $_POST['time2_1']
));

最佳答案

只需绑定(bind)所有值即可。

$sql = "INSERT INTO tbl_name (max, time1, time2) VALUES (?,?,?)".str_repeat(',(?,?,?)', 9);
$stmt = $db->prepare($sql);
$params = array();
for ($i = 1; $i <= 10; $i++) {
$params[] = $_POST['max'];
$params[] = $_POST["time1_$i"];
$params[] = $_POST["time2_$i"];
}
$stmt->execute($params);

关于PHP PDO 将多行/值插入到 mySQL 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24392664/

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