Mysql - PHP - 查看总和列

时间:2015-05-23 06:26:43

标签: php mysql sql select mysqli

我如何查看列(集合)的总和(userid = $ userid)?

示例:我需要查看用户id = 2,Collections = 200 + 330 = 530的结果,我需要查看此结果( 530

我的表

------------------------------
| id | user_id | Collections |
------------------------------
| 1  |    2    |     200     |
------------------------------
| 2  |    2    |     330     |
------------------------------
| 3  |    7    |     120     |
------------------------------
| 4  |    8    |     760     |
------------------------------
| 5  |    9    |     200     |
------------------------------
| 6  |    9    |     100     |
------------------------------

我的代码

<?php

$user_id = get_current_user_id();

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$query = "SELECT SUM(Collections) FROM invoices where user_id = $user_id"; 

$result = mysql_query($query) or die(mysql_error());



// Print out result

?>
  • 我是php&amp;的初学者MySQL的

3 个答案:

答案 0 :(得分:2)

你可以试试这个:

SELECT SUM(i.Collections) AS totalCollection
FROM invoices AS i
WHERE i.user_id = '$user_id'
GROUP BY i.user_id

答案 1 :(得分:0)

试试这个

SELECT SUM(Collections) AS totalvalue FROM invoices where user_id = '$user_id'

打印结果totalvalue

答案 2 :(得分:0)

<强>第一

  • 检查您的收集列类型。是String / Int / Date吗?它应该是数字(Int,double,float)

<强>第二

  • 您的查询已经正确无误。但列名称应将其更改为结果
SELECT SUM(Collections) as result FROM invoices where user_id = $user_id

然后检查你的功能,从使用 mysqli 的连接,但在你的查询中你正在使用 mysql 这个应该被改为同一个功能。

<强>解决方案

<?php

$user_id = get_current_user_id();

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$query = "SELECT SUM(Collections) FROM invoices where user_id = $user_id"; 

$result = mysqli_query($link, $query) or die('query error');

print_r($result);
// Print out result

?>