新人在这里!
我正在建立一个由mysql驱动的自定义购物车,并且我试图按数量更新我的购物车项目。看来我做错了,因为当我尝试更新数量时,它只会更新最后一个项目。我在下面发布代码。任何帮助,将不胜感激。提前致谢。

1.cart.php:
    
    

    $sql = "select * from orders";
    $result = mysql_query($sql);
    $num = mysql_num_rows($result);
    echo "Στοιχεία: ".$num;
    ?>
    <form name="cart" method="post" action="updatecart.php">
      <table border="2">
        <tr>
          <td>Α/Α</td>
          <td>img_name</td>
          <td>Reprints</td>
          <td>Color</td>
        </tr>
        <?php
        if($num){
            while ($row = mysql_fetch_array($result)){
             ?>
                <tr>
                  <td><?php  echo $row['item_id']; ?></td>
                  <td><?php echo $row['img_name']; ?></td>
                  <td><input type="number" name="quantity" value="<?php echo $row['quantity']; ?>"></td>
                  <input type="hidden" name="item_id" value="<? echo $row['item_id']; ?>">
                  <td><?php echo $row['color']; ?></td>
                </tr>
            <?php
            }
        }

            ?>
      </table>
      <input type="submit" name="update" value="Update Cart" />
      <input type="button" name="2checkout" value="Proceed to Checkout" />
</form>


2.updatecart.php

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<?php
    $database_name = "vog";
    $conn = mysql_connect("localhost","root","toor");
    mysql_select_db($database_name);

    $num = 2; //na to ferw me session meta edw!
    if(isset($_POST['update'])){
        $item_id = $_POST['item_id'];
        $i=1;

        while($i<=$num){
            $item_id = $_POST['item_id'][$i];
            $quantity = $_POST['quantity'];
            $sql2 = "update orders SET quantity = '$quantity' where item_id = '$item_id' ";
            $result2 = mysql_query($sql2) or die ("Error in query: $result2");
            $i++;
        }
    }

    if(isset($result2)){
        header("Location:cart.php");
    }
?>


到目前为止,它仅更新最后一条记录。

最佳答案

在#1.cart.php中,将输入用作数组:

<input type="number" name="quantity[<?php  echo $row['item_id']; ?>]" value="<?php echo $row['quantity']; ?>">
<input type="hidden" name="item_id[<?php  echo $row['item_id']; ?>]" value="<? echo $row['item_id']; ?>">


并在#2.updatecart.php中进行处理

 foreach($_POST['item_id'] as $key => $id){

 $item_id = $id;
 $quantity = $_POST['quantity'][$key];
 $sql2 = "update orders SET quantity = '$quantity' where item_id = '$item_id' ";
 $result2 = mysql_query($sql2) or die ("Error in query: $result2");
 $i++;

 }

关于php - 更新购物车-MySQL表更新-while循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8338774/

10-12 00:17
查看更多