【发布时间】:2016-03-20 20:42:04
【问题描述】:
如何通过foreach循环在sql中插入多个值?
(它只向我插入最后一个值而不是全部,如果我在 sql 中添加更多值,那么当在 foreach 循环中只有一个值时,它会复制我的插入数据。 如何在我的 sql 中添加唯一编号作为每次插入的订单 ID? 这是我的代码...
<?php include'header_nav.php'; ?>
<div class="mainContent_u">
<h1> Your shopping Chart<br/>contains ...</h1>
<table class="show_cart">
<tr>
<th><strong><h3>Book Title</strong></h3></th>
<th><strong><h3>Quantity</strong></h3></th>
<th><strong><h3>Price</strong></h3></th>
<th><strong><h3>Total</strong></h3></th>
</tr>
<?php
require 'connect_db.php';
$totalPrice = 0;
foreach($_POST as $name => $value){
if(is_numeric($value) && $value != 0 && $name != "submit"){
$sql = "SELECT id,book, price from add_item WHERE id = ".$name;
$result=mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);
$price = $row['price'] * $value;
$price = number_format($price,2);
$totalPrice = $totalPrice + $price;
$totalPrice = number_format($totalPrice,2);
$qty = $value;
$sql = "INSERT INTO orders (order_id,book_name, quantity, price_pb, price_total) VALUES ('" . $row['id'] . "','" . $row['book'] . "','" . $qty . "','" . $row['price'] . "','" . $price . "')";
echo "<tr>";
echo "<td>".$row['book']."</td><td>".$value."</td><td>€".$row['price']."</td><td>€".$price."</td>";
echo "</tr>";
}
}
echo "</table>";
echo "<strong><h3>Total Price: €".$totalPrice."</h3></strong>";
?>
<p><strong>Review your shopping cart and then proceed to checkout.</strong></p>
<a href="checkout.php"><button class="submit" >Proceed to Checkout</button></a>
</div>
<?php include'footer.php'; ?>
如果您需要任何其他信息,请告知。
还有,为什么这个 else 语句不起作用。
foreach($_POST as $name => $value){
if(is_numeric($value) && $value != 0 && $name != "submit"){
$sql = "SELECT id,book, price from add_item WHERE id = ".$name;
$result=mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);
$price = $row['price'] * $value;
$price = number_format($price,2);
$totalPrice = $totalPrice + $price;
$totalPrice = number_format($totalPrice,2);
$qty = $value;
$sql = "INSERT INTO orders (order_id,book_name, quantity, price_pb, price_total) VALUES ('" . $row['id'] . "','" . $row['book'] . "','" . $qty . "','" . $row['price'] . "','" . $price . "')";
echo "<tr>";
echo "<td>".$row['book']."</td><td>".$value."</td><td>€".$row['price']."</td><td>€".$price."</td>";
echo "</tr>";
}else {header('location:all_books.php');}
}
谢谢,
【问题讨论】: