简体   繁体   English

如何在php中对MySQL表列求和?

[英]How to sum of MySQL table column in php?

I want to get the sum total of the table columns in my database.我想获取数据库中表列的总和。 I've tried using the following code but have not been successful.我尝试使用以下代码但没有成功。

$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(value) AS value_sum FROM  User_Table'); 
$row = mysqli_fetch_assoc($result); 
$sum = $row['value_sum'];
echo $sum;  

Thank you very much!!非常感谢!!

As of my understanding you need count the number of columns your database have.据我了解,您需要计算数据库的列数。 If I am not wrong, you may please use the query below如果我没有记错,您可以使用下面的查询

select * from information_schema.columns
where table_schema = '<YOUR DATABASE NAME>'
order by table_name,ordinal_position

Hope this helps.希望这会有所帮助。 Thanks谢谢

I hope you try to find total number of record of a table of User_Table我希望您尝试查找 User_Table 表的总记录数

$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(your_column_name) AS value_sum FROM  User_Table'); 
//or like the query for return last row that indicate total number of record 
// id auto increment
$result = mysqli_query($link,'SELECT * FROM User_Table ORDER BY id DESC LIMIT 1;'); 
$row = mysqli_fetch_assoc($result); 
$sum = $row['id'];
echo $sum;  

// or using count
    $result = mysqli_query($link,'SELECT COUNT(*) total_row FROM User_Table;'); 
    $row = mysqli_fetch_assoc($result); 
    $sum = $row['total_row '];
    echo $sum; 

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

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