-1

我想将我的数据插入数据库,但是,它不能正常工作,例如,当我将 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>
4

1 回答 1

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());

    }
于 2013-04-12T23:37:39.723 回答