[英]Insert several rows into MySQL table at once
我一直在努力,我能夠得到我想要的結果。 事實上,這是一個非常簡單的過程。
我所做的是將輸入中的信息保存為矩陣,然后遍歷它並在每個循環之后執行查詢,就這么簡單。
我提供了一些示例代碼。 它們與我在問題中提供的表格不同,但原理是相同的。
我做的第一件事是格式化輸入的名稱,如下所示。 它使循環 arrays 變得更容易。 這部分的功勞屬於這篇文章的第一個答案: Submitting a multidimensional array via POST with php
<tr>
<td><input name="info[0][top]" value="tr 1/ td 1" /></td>
<td><input name="info[0][bottom]" value="tr 1/ td 2" /></td>
</tr>
<br/>
<tr>
<td><input name="info[1][top]" value="tr 2/ td 1" /></td>
<td><input name="info[1][bottom]" value="tr 2/ td 2" /></td>
</tr>
<br/>
<tr>
<td><input name="info[2][top]" value="tr 3/ td 1" /></td>
<td><input name="info[2][bottom]" value="tr 3/ td 2" /></td>
</tr>
之后,我只是在執行查詢之前遍歷來自表單的數據。
$query = "INSERT INTO tb_teste (teste_info1, teste_info2) VALUES (:teste_info1, :teste_info2)";
$stmt = $this->conexao->prepare($query);
$el = $this->teste->__get('teste_info1');
$i = 0;
foreach ( $el as $item ) {
$stmt->bindValue(':teste_info1', $this->teste->__get('teste_info1')[$i]['top']);
$stmt->bindValue(':teste_info2', $this->teste->__get('teste_info1')[$i]['bottom']);
$stmt->execute();
$i++;
}
關於動態行數的需要,我將在 JavaScript 中為生成的每個 id 創建一個輸入,並將“info”的索引分配給一個變量,該變量將根據需要遞增。 這會給我我需要的一切。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.