上午
我正在尝试基于查询与用户会话相关联的mysql db列数据来编写php mysqli sum查询。因此,脚本应该在A列中获取与会话用户名关联的所有数据库数据,然后从列B中提取变量,然后对与列B变量匹配的列C值求和。
继承我拥有的东西,结果产生0,而不是销售列C中的数据总和。
DB表看起来像:
Column A / Column B / Column C
Bill / Sales / 15.00
Helen / Sales / 32.00
James / Accounts / 20.00
..
目前的代码如下:
<?php
session_start();
$db = new mysqli('DBHOST.com', 'DBUsername', 'DBPassword', 'DBNAME');
if ($db->connect_errno > 0) {
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = mysqli_query($db, "SELECT * FROM Table_Name WHERE ColumnA = '" . $_SESSION["username"] . "'");
$count = mysqli_num_rows($sql);
if ($count == 1) {
$output = mysqli_fetch_assoc($sql);
$columnBresult = trim($output['ColumnB']);
}
$sumquery = mysqli_query($db, "SELECT SUM(ColumnC) as total FROM Table_Name WHERE ColumnB = '$columnBresult'");
$row = mysqli_fetch_assoc($sumquery);
$sum = $row['total'];
echo $sum > 0 || $sum !== null ? $sum : "0";
?>
欢迎任何想法..
答案 0 :(得分:1)
除了检查之外,$_SESSION['username']
变量中还有任何用户名值。此外,您可以通过连接同一个表来实现单个查询的计算:
数据库表:
mysql> select * from table_name;
+---------+----------+---------+
| ColumnA | ColumnB | ColumnC |
+---------+----------+---------+
| Bill | Sales | 15 |
| Helen | Sales | 32 |
| James | Accounts | 20 |
+---------+----------+---------+
3 rows in set
查询:
SELECT
SUM(t1.ColumnC) AS total
FROM
table_name t1
INNER JOIN table_name t2 ON t1.ColumnB = t2.ColumnB
WHERE
t2.ColumnA = 'Bill'
结果:
+-------+
| total |
+-------+
| 47.00 |
+-------+
1 row in set
答案 1 :(得分:0)
修正了它:
<?php
session_start();
$db = new mysqli('DBHost.com', 'DBUsername', 'DBPassword', 'DBName');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = mysqli_query($db, "SELECT ColumnB FROM Table_Name WHERE ColumnA = '".$_SESSION["username"]."'");
$fetch = mysqli_fetch_assoc($sql);
$dept = $fetch['ColumnB'];
$result = mysqli_query($db, "SELECT SUM(ColumnC) AS total FROM Table_Name WHERE ColumnB = '$dept'");
$row = mysqli_fetch_assoc($result);
$sum = $row['total'];
echo $sum > 0 || $sum!==null ? $sum : "0";
?>
这对我有用。