简体   繁体   English

如何使用多个SUM()进行mySQL语句?

[英]How do I make a mySQL statement with more than one SUM()?

My site adds product identifiers to a session variable (an array called "itemarray") when a button is clicked on the product page. 当在产品页面上单击按钮时,我的网站将产品标识符添加到会话变量(称为“ itemarray”的数组)中。 When the user opens their shopping cart, the following code executes: 用户打开购物车时,将执行以下代码:

<?php
    $cart = implode(',', $_SESSION['itemarray']);
    /*Create connection to DB here. DB connection is called $connection.*/
    $result = $connection->query("SELECT SUM(Price) AS Total_Price, SUM(Tax) AS Total_Tax, SUM(Shipping) AS Total_Shipping FROM STOCK_LIST WHERE Product_ID IN ($cart)");
    while ($rows = $result->fetch_assoc()) {
        /*Output query result into table*/
    }
    /*Terminate the connection to the database*/
    $connection->close();
?>

The first line of code goes through the itemarray and appends each element into a comma-delimited list (called $cart). 代码的第一行通过itemarray,并将每个元素附加到以逗号分隔的列表(称为$ cart)中。 A connection is made to the database (the code for which has been removed because it has already been tested), and a query is submitted which asks for the total price, tax, and shipping costs of the items in $cart. 与数据库建立连接(由于已经对其进行了测试,因此已删除其代码),并提交查询以询问$ cart中商品的总价格,税金和运费。 A while loop is then run which echos the contents of the $results variable into a table (the code for which has been removed because it has already been tested). 然后运行while循环,该循环将$ results变量的内容回显到表中(由于已经对其进行了测试,因此已删除了该代码)。

The issue is that the calculated totals aren't being output. 问题是没有输出计算出的总数。 The implode function works as expected, the connection is being made, and the table is being created (just without the output from the query), so I can only assume that the query is the problem. implode函数按预期工作,正在建立连接,并且正在创建表(只是没有查询的输出),所以我只能假设查询是问题所在。

I changed the implode command to: 我将implode命令更改为:

$cart = implode('\', \'', $_SESSION['itemarray']);

This puts the list into the following format: 这会将列表放入以下格式:

1', '2 1','2

Where 1 and 2 are both product IDs. 其中1和2均为产品ID。 In order to add the single quotes to beginning and end of the string, I then added: 为了将单引号添加到字符串的开头和结尾,然后添加了:

$cart = "'" . $cart . "'";

Adding this second line of code changes the contents of $cart into this: 添加第二行代码会将$ cart的内容更改为:

'1'. '1'。 '2' '2'

This can now be used in my SQL statement. 现在可以在我的SQL语句中使用它。

I would strongly recommend you using binding parameters as it will save your site from SQL injection attack (which I assume would be crucial for your shop site). 我强烈建议您使用绑定参数,因为它将使您的网站免受SQL注入攻击(我认为这对您的商店站点至关重要)。 Try to adopt the solution from this question . 尝试采用此问题的解决方案。

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

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