简体   繁体   English

我将如何在php mysql中的一个变量中获取2个不同的行?

[英]What will I do to get 2 different rows in one variable in php mysql?

What am I trying to do is when the customer buys from my cart, the quantity of the product will be subtracted from the quantity the customer buys? 我想要做的是当顾客从我的购物车购买时,产品的数量将从顾客购买的数量中减去? I'm expecting multiple products the customer will buy. 我期待客户会购买多种产品。

Here's my code. 这是我的代码。

$x=$_SESSION['products'];
        foreach($x as $id => $y){ 
        $insert_row = $mysqli->query("INSERT INTO transaction 
        VALUES (null,'$buyerName','$buyerEmail','$transactionID','$y[code]','$y[qty]',NOW(),'Pending')");
        $result1=mysql_query("SELECT quantity from products where product_code='$y[code]'");
        if(mysql_num_rows($result1)>0){
            $row=mysql_fetch_object($result1);
            $currqty=$row->quantity;
            echo "".$currqty;
        }else{
            echo "No record found";
        }
SELECT GROUP_CONCAT(product) AS res FROM table WHERE foo=1 GROUP BY foo;

that way you will have a list of all products in "res" matching on foo=1, while getting just one row. 这样你就可以在foo = 1的“res”匹配中找到所有产品的列表,同时只获得一行。

find more about group_concat here: 在此处查找有关group_concat的更多信息:

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

If the purpose of your code is to substract the quantity from products after a successful insert into transaction , here is an optimized version of your code, that achieves this: 如果您的代码的目的是在成功插入事务后从产品中减去数量,那么这是您的代码的优化版本,它实现了这一点:

foreach($_SESSION['products'] as $id => $y) {
    $insert_row = $mysqli->query("
        INSERT INTO transaction
        VALUES (null,'$buyerName','$buyerEmail','$transactionID','$y[code]','$y[qty]',NOW(),'Pending')"
    );
    if($insert_row) {
        ## Important: substract the quantity from products only if a successful 
        ##            insert has been made in the transaction table
        $result1 = mysql_query("UPDATE products SET quantity = quantity - {$y[qty]} WHERE product_code='$y[code]'");
        if($result1) {
            echo "quantity updated";
        }
    }
}

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

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