使用php将多行插入mysql数据库

时间:2017-12-04 08:34:58

标签: php mysql

一次将多行数据插入表格时出现问题。以下是我所拥有的。当我点击提交时,只插入最后一行,只有数量的第一个数字。请帮忙。

html表格:

<form method="post" action="insert.php">
<p><input type="text"  id="product_id" name="product_id[]"/>  
   <input type="text" id="quantity" name="quantity[]"/></p>
<p><input type="text"  id="product_id" name="product_id[]"/>  
   <input type="text" id="quantity" name="quantity[]"/></p>
<p><input type="text"  id="product_id" name="product_id[]"/>  
   <input type="text" id="quantity" name="quantity[]"/></p>
<input type="submit" name="submit" value="submit"/>
</form>

insert.php页面:

<?php 
include 'config/auth.php';//database connection 
if(isset($_POST['submit'])){
    $product = mysqli_real_escape_string($dbc, $_POST['product_id']);
    $quantity = mysqli_real_escape_string($dbc, $_POST['quantity']);
    $count = sizeof($product);
    for ($i=0; $i < $count; $i++) { 
        $Inproduct = $product[$i];
        $Inquantity = $quantity[$i];
    $query = "INSERT INTO sales (product_id, quantity) VALUES ('$Inproduct','$Inquantity')";
    $results = mysqli_query($dbc, $query);
    }
    if ($results) {
        echo 'Success';
    }
}
?>

1 个答案:

答案 0 :(得分:0)

以下代码有效...感谢@kmdm

    $product = $_POST['product_id'];
    $quantity = $_POST['quantity'];
    $count = sizeof($product);
    for ($i=0; $i < $count; $i++) { 
        $Inproduct = mysqli_real_escape_string($dbc, $product[$i]);
        $Inquantity = mysqli_real_escape_string($dbc, $quantity[$i]);
    $query = "INSERT INTO sales (product_id, quantity) VALUES ('$Inproduct','$Inquantity')";
    $results = mysqli_query($dbc, $query);
    }