如何使用PHP和MYSQL将多行插入表中?

时间:2019-05-10 12:46:26

标签: php mysql mysqli

我需要用两个不同的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;
?>

1 个答案:

答案 0 :(得分:0)

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>

但是您只会得到一个值-不记得它是第一个还是最后一个,但是快速的Google很快就会告诉您。如果要提交多个值,则需要在表单<input type="text" name="title[]"...

上提供唯一的名称,以供使用post数组语法

然后,当您执行插入循环时,您将可以通过说出正确的值

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

您需要var_dump您的一些变量,以便您可以看到正在发送的数据,因为我非常有信心,它与您认为要获取的数据不同

相关问题