我想将数据插入到数据库中,但是,它没有正常工作,例如,当我将4个产品添加到购物车时,它只会插入两个中的两个。并且小计显示为它将产品的第一个数量捕获为我的小计,然后它显示整个产品的总数量。我的数量不会插入我的数据库中。
<table>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price per item</th>
<th>Total cost</th>
</tr>
<?php
$sql = "SELECT * FROM productsc WHERE id_product IN (";
foreach ($_SESSION['cartCity'] as $id => $value) {
$sql .= $id . ",";
}
$sql = substr($sql, 0, -1) . ") ORDER BY name ASC";
$query = mysql_query($sql);
$total_price = 0;
if (!empty($query)) {
while ($row = mysql_fetch_assoc($query)) {
$subtotal = $_SESSION['cartCity'][$row['id_product']]['quantity'] * $row['price'];
$total_price += $subtotal;
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><input type="text" name="quantity-<?php echo $row['id_product']; ?>" size="5" value="<?php echo $_SESSION['cartCity'][$row['id_product']]['quantity']; ?>" /></td>
<td><?php echo "$" . $row['price']; ?></td>
<td><?php echo"$" . $_SESSION['cartCity'][$row['id_product']]['quantity'] * $row['price']; ?></td>
</tr>
<?php
if ($row = mysql_fetch_assoc($query)) {
$sql2 = "INSERT INTO order_details (name,quantity,price,subtotal) VALUES ('" . $row['name'] . "','" . $quantity . "','" . $row['price'] . "','" . $total_price . "')";
$query2 = mysql_query($sql2) or die(mysql_error());
}
}
}
?>
<tr>
<td></td>
<td></td>
<td>Total price:</td>
<td><?php echo"$" . $total_price; ?></td>
</tr>
</table>
答案 0 :(得分:0)
可能是因为你在循环中调用$ row = mysql_fetch_assoc($ query)做同样的事情,这意味着外循环只会运行一半的时间而你只会输入其他每一项
试
while ($row = mysql_fetch_assoc($query)) {
$subtotal = $_SESSION['cartCity'][$row['id_product']]['quantity'] * $row['price'];
$total_price += $subtotal;
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><input type="text" name="quantity-<?php echo $row['id_product']; ?>" size="5" value="<?php echo $_SESSION['cartCity'][$row['id_product']]['quantity']; ?>" /></td>
<td><?php echo "$" . $row['price']; ?></td>
<td><?php echo"$" . $_SESSION['cartCity'][$row['id_product']]['quantity'] * $row['price']; ?></td>
</tr>
<?php
$sql2 = "INSERT INTO order_details (name,quantity,price,subtotal) VALUES ('" . $row['name'] . "','" . $quantity . "','" . $row['price'] . "','" . $total_price . "')";
$query2 = mysql_query($sql2) or die(mysql_error());
}