2014-06-24 95 views
0

我正在將此表單提交到mySQL數據庫中的表中。字段max對於所有行都是相同的,但每行都有2個唯一值。PHP PDO將多行/值插入到mySQL表中

<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'] 
    )); 
+1

您可以準備一次語句,並在一個循環中執行不同的值數組。 – feeela

回答

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); 
+0

謝謝。我會試試看 – Azukah