首页 > 解决方案 > 如何使用 PHP 和 MYSQL 在表中插入多行?

问题描述

我需要INSERT INTO两个不同的表和两个不同的INSERT语句。第一个工作正常,第二个工作正常,但是,INSERT INTO第二个表可以有几行,但这只会插入一行。我认为for循环会起作用,但它并没有给我我需要的东西。

$productID = $_POST['product_id'];
$title = $_POST['title'];
$productQty = $_POST['qty'];

if(empty($hNum) || empty($street) || empty($city) || empty($county) || empty($postcode) || empty($country)){
  header("Location: checkout.php?error=emptyaddressfields");
  exit();
}
else {
  $sql = "INSERT INTO orders (customer_id, order_date, order_status, num_items, total_cost)
              VALUES ('$customer_id', CURRENT_TIMESTAMP, 'Order Placed', '$num_items', '$total_cost')";

  if(mysqli_query($conn, $sql)){
    for($i=0; $i < $productQty; $i++) {
      $sqlOI = "INSERT INTO order_item (order_id, product_id, title, quantity)
                VALUES (
                  (SELECT MAX(order_id) FROM orders),
                  '$productID',
                  '$title',
                  '$productQty'
                  )";
    }
    if(mysqli_query($conn, $sqlOI)){
      header("Location: account.php?success=orderPlaced");
      exit();
    } 
    else {
      echo "Something went wrong...".mysqli_error($conn);
    }
  }
}

如果有其他类型的循环会更好,请告诉我。我在网上搜索了不同的方法来做到这一点,但要么没有意义,要么不起作用。如果我在命令行中运行第二个INSERT语句(没有变量)它可以工作,所以我知道问题不是SQL.

任何帮助深表感谢。

编辑:数据显示在表格中,当另一个产品添加到会话数组中时,会添加一个新行。HTML 表中的每一行都是由添加到“购物车”的产品生成的。每一行都有相同的<tr> <td><input>属性。因此,当添加另一个产品时,它会生成一个新行,name="id"名称相同或其他。

<?php
   if(!empty($_SESSION['shopping_cart'])):
     $total = 0;
     $cart_qty = 0;
     foreach($_SESSION['shopping_cart'] as $key => $product):

     <tr>
      <td hidden><input type="text" name="product_id" value="<?php echo $product['product_id']; ?>"></td>
       <td><input type="text" name="title" value="<?php echo $product['title']; ?>"></td>
       <td><input type="text" name="qty" value="<?php echo $product['quantity']; ?>"></td>
       <td>£<?php echo $product['price']; ?></td>
       <td>£<?php echo number_format($product['quantity'] * $product['price'], 2); ?></td>
     </tr>

     $total = $total + ($product['quantity'] * $product['price']);
     $cart_qty = $cart_qty + ($product['quantity']);
   endforeach;
?>

标签: phpmysqlmysqli

解决方案


for($i=0; $i < $productQty; $i++) {
      $sqlOI = "INSERT INTO order_item (order_id, product_id, title, quantity)
                VALUES (
                  (SELECT MAX(order_id) FROM orders),
                  '$productID',
                  '$title',
                  '$productQty'
                  )";
    }//bottom of for loop
    if(mysqli_query($conn, $sqlOI)){//execution
      header("Location: account.php?success=orderPlaced");
      exit();
    } 

您只执行最后一个循环,因为您每次都会覆盖您的 sql 字符串。至少你应该在 for 循环中移动执行,但实际上你应该做类似的事情

$sql = [];//create an empty array

    for($i=0; $i < $productQty; $i++) {
//insert a  an update row
$sql[] = "VALUES ((SELECT MAX(order_id) FROM orders),:pdo_placeholder" . $I . ",.....)"
        }

//implode the rows into a final string then do the connection
 $sql = "INSERT INTO order_item 
(order_id, product_id, title, quantity) VALUES " .  implode(',',$sql);



//now we are outside the loop we can execute
//lets assume you've changed this to a properly prepared pdo execute statement and get the max id correctly for your query

if(mysqli_query($conn, $sqlOI)){
   header("Location: account.php?success=orderPlaced");
   exit();
 } 

这样你只需要做1个连接。我将假设您将听取有关使用准备好的陈述和遗嘱的评论建议。 - 更新 -

根据您在下面的评论,我将添加以下内容:

你永远不会更新你的变量。让我们只取 1

$title = $_POST['title'];

这是设置一次,并且永远不会如此逻辑地更新循环的每次迭代都会插入相同的值。在您的表单中,您对输入使用相同的名称:

 <td><input type="text" name="title" value="<?php echo $product['title']; ?>"></td>

但是你只得到一个值——不记得是第一个还是最后一个,但快速的谷歌很快就会告诉你。如果要提交多个值,则需要提供唯一名称以在表单上使用后数组语法 <input type="text" name="title[]"...

然后当您执行插入循环时,您将能够通过说来访问正确的值

$title = $_POST['title'][$i];

您需要 var_dump 一些变量,以便您可以看到您发送的数据是什么,因为我相当有信心它与您认为您获得的数据不同


推荐阅读