简体   繁体   中英

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

$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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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