簡體   English   中英

PHP PDO將多個行/值插入mySQL表

[英]PHP PDO insert multiple rows/values into mySQL table

我正在將此表單提交到mySQL db中的表中。 所有行的字段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']
    ));

只需綁定所有值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM