简体   繁体   English

如果ID在MySQL中相同,则合并两行

[英]Merge two rows if ID is the same in MySQL

How to combine the product's quantity into a single row if the Product ID is the same? 如果产品ID相同,如何将产品数量合并为一行? This is for my customer's cart. 这是给我客户的购物车的。 When I add to cart a product, I want it to combine into a single row instead of a seperate row. 当我将产品添加到购物车时,我希望将其合并为单行而不是单独的行。

EDIT: I have two tables which contains a seperate quantity field (tblproducts, tblcart). 编辑:我有两个表,其中包含一个单独的数量字段(tblproducts,tblcart)。

EDIT2: PHP is giving me an error EDIT2:PHP给我一个错误

mysqli_fetch_array() expects parameter 1 to be mysqli_result boolean given on my line 61 mysqli_fetch_array()期望参数1是我的第61行给出的mysqli_result布尔值

              <?php 
            $query = "SELECT * FROM products";
            $exec = mysqli_query($connection, $query);
            $a = 1;
            $b = 1;
            while ($row = mysqli_fetch_array($exec)) {

but my code works just fine. 但我的代码工作正常。 Can anyone find the problem? 谁能找到问题?

Code for my customer's cart 我的客户购物车的代码

        <table class="table table-hover">
      <thead>
        <tr>
          <th>Product ID</th>
          <th>Product Name</th>
          <th>Description</th>
          <th>Quantity</th>
          <th>Price per Unit</th>
          <th>Total Amount</th>
          <th>Remove</th>
        </tr>
      </thead>
      <tbody>


      <?php 

        $selectCart = "SELECT * FROM cart INNER JOIN products ON products.product_id = cart.product_id";
        $execSelectCart = mysqli_query($connection, $selectCart);

        while ($row = mysqli_fetch_array($execSelectCart)) {

          $cartProId = $row['product_id'];
          $cartProName = $row['product_name'];
          $cartProDesc = $row['description'];
          $cartSellPrice = $row['sell_price'];
          $cartQty = $row['quantityCart'];

          $compute = $cartSellPrice * $cartQty;
          $totalAmount = number_format((float)$compute, 2, '.', '');
       ?>

        <tr>
          <td><?php echo $cartProId; ?></td>
          <td><?php echo $cartProName; ?></td>
          <td><?php echo $cartProDesc; ?></td>
          <td><?php echo $cartQty; ?></td>
          <td><?php echo $cartSellPrice; ?></td>
          <td><?php echo $totalAmount ?></td>
          <td class="text-center">
            <div class="btn-group">
              <a href="edit_brand.php?brand_id=<?php echo $brand_id; ?>"  class="btn btn-xs btn-info" data-toggle="tooltip" title="Edit">
                <span class="glyphicon glyphicon-edit"></span>
              </a>
              <a href="manage_brands.php?delete=<?php echo $brand_id; ?>"  class="btn btn-xs btn-danger" data-toggle="tooltip" title="Remove">
                <span class="glyphicon glyphicon-trash"></span>
              </a>
            </div>
          </td>
        </tr>

      <?php } ?>
      </tbody>
    </table>

Code for adding a product 添加产品的代码

<?php
   if (isset($_POST['addCart']) && $_POST['addCart']=="Add Items to Cart") {
     foreach($_POST['qtyBuy'] as $index=>$value){
       if($value > 0){
        $cartID = $_POST['product_id'][$index];
           $addQuery = "INSERT INTO cart (product_id, quantityCart) VALUES (".$_POST['product_id'][$index].", ".$value.");";
           $addQuery .= "UPDATE products SET quantity = quantity - $value WHERE product_id = $cartID;";
           $execQuery = mysqli_multi_query($connection, $addQuery);
        }  
     }
     header('Refresh: 0; url=add_sales.php');
  }
?>

<div class="row">
  <div class="col-md-12"> <!-- Product List Info Start -->
    <div class="panel panel-default">
      <div class="panel-heading">
        <strong>
          <span class="glyphicon glyphicon-th"></span>
          <span>Select Products</span>
       </strong>
      </div>

      <div class="panel-body">
        <div class="form-group pull-left">
           <input type="text" class="search form-control" placeholder="Search products">
         </div>
         <span class="counter pull-left"></span>
          <div class="span3">

              <form action="add_sales.php" method="POST">
            <table class="table table-striped table-bordered table-hover results table-fixed">
              <thead>
                <tr>
                    <th class="text-center">#</th>
                    <th>Product Name</th>
                    <th>Description</th>
                    <th>Price</th>
                    <th>In Stock</th>
                    <th style="width: 20%">Quantity</th>
                </tr>
                <tr class="warning no-result">
                  <td colspan="8"><i class="fa fa-warning"></i> No Product Found</td>
                </tr>
              </thead>


              <tbody>
              <?php 
                $query = "SELECT * FROM products";
                $exec = mysqli_query($connection, $query);
                $a = 1;
                $b = 1;
                while ($row = mysqli_fetch_array($exec)) {

                  $product_id = $row['product_id'];
                  $product_name = $row['product_name'];
                  $product_price = $row['sell_price'];
                  $description = $row['description'];
                  $product_quantity = $row['quantity'];

               ?>
              <tr>
              <td class="text-center"><?php echo $product_id; ?>
                <input type="hidden" name="product_id[]" value="<?php echo $product_id; ?>">
              </td>
                  <td><?php echo $product_name; ?></td>
                  <td><?php echo $description; ?></td>
                  <td><?php echo $product_price; ?></td>
                  <td><input type="number" name="hehe" value="<?php echo $product_quantity; ?>" id="<?php echo "qtyResult" . $a++; ?>" disabled></td>
                  <td><input type="number" name="qtyBuy[]" id="<?php echo "qtyBuy" . $b++; ?>" onkeyup="updateStock(this, event)"></td>
              </tr>
              <?php } ?>
              </tbody>
          </table>


          </div>
          <div class="form-group">
              <input type="submit" name="addCart" value="Add Items to Cart" class="btn btn-info pull-right">

          </div>
          </form>

Table's image 桌子的形象

在此处输入图片说明

If I understand, your basic problem is that you allow the database to store the same product ID multiple times under the same cart in the cart table. 据我了解,您的基本问题是,您允许数据​​库在cart表中的同一购物车下多次存储相同的产品ID。 My solution relies on the presence of a field that has the same value for all items in the same cart. 我的解决方案依赖于一个字段,该字段对于同一购物车中的所有项目具有相同的值。 I use cart_id but it could be something else. 我使用cart_id但可能还有其他原因。

Since you want a product to appear only once in the same cart, you should do two things: 由于您只希望产品在同一购物车中出现一次,因此您应该做两件事:

1. Add a UNIQUE INDEX(cart_id, product_id) the cart table. 1.cart表中添加一个UNIQUE INDEX(cart_id, product_id) Once you've done this any attempt to add the same product to the same cart will fail with an error. 完成此操作后,将相同产品添加到同一购物车的任何尝试均将失败并显示错误。 Run this query just once: 仅运行一次此查询:

ALTER TABLE `cart` ADD UNIQUE INDEX (cart_id, product_id);

2. Change the query you use to add items to cart. 2.更改用于向购物车添加项目的查询。 As I pointed out above, a regular INSERT will fail if the product is already in that cart. 正如我在上面指出的那样,如果该产品已经在购物车中,则常规INSERT将会失败。 Instead, use INSERT...ON DUPLICATE KEY UPDATE... query. 而是使用INSERT...ON DUPLICATE KEY UPDATE...查询。 This query will insert the product id if it's not found. 如果找不到,此查询将插入产品ID。 However if the cart already has that product, the query will update the existing record. 但是,如果购物车已具有该产品,则查询将更新现有记录。

Change: 更改:

INSERT INTO cart (product_id, quantityCart) 
    VALUES (".$_POST['product_id'][$index].", ".$value.")

To: 至:

INSERT INTO cart (cart_id, product_id, quantityCart) 
    VALUES ($cartID, {$_POST['product_id'][$index]}, $value)
ON DUPLICATE KEY UPDATE quantityCart = quantityCart + $value

I used cart_id in my solution as the way to determine all items that belong to the same cart. 我在解决方案中使用cart_id作为确定属于同一购物车的所有商品的方式。 If you have another field that does this (eg: user_id ), use that instead of cart_id . 如果您有另一个执行此操作的字段(例如: user_id ),请使用该字段代替cart_id The basic solution is the same. 基本解决方案是相同的。

Suppose you have this table 假设你有这张桌子

id employee_id contract_id month year d1 d2 d3 1 25 1 11 2011 1 01 01 2 16 5 11 2011 1 11 0 3 29 3 11 2011 1 001 100 1 25 4 11 2011 0 11 011

You want to merge this on the basis of Id, In your case its product_id 您想基于Id合并它,在您的情况下是product_id

    id  employee_id contract_id      month    year    d1     d2      d3
    1          25        1,4            11       2011    1,0    01,11   01,011
    2          16        5              11       2011    1      11      0
    3          29        3              11       2011    1      001     100

You can do that by this query 您可以通过此查询来做到这一点

SELECT
    id,
    employee_id,
    GROUP_CONCAT(contract_id SEPARATOR ',') AS contract_ids,
    `month`,
    `year`,
    GROUP_CONCAT(d1 SEPARATOR ',') AS d1s,
    GROUP_CONCAT(d2 SEPARATOR ',') AS d2s,
    GROUP_CONCAT(d3 SEPARATOR ',') AS d3s
FROM
    `table`
WHERE
    `month` = 11 AND `year` = 2011
GROUP BY
    employee_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM