使用 PHP 计算 MySQL 中列值的所有值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17878878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:37:51  来源:igfitidea点击:

Count all values from column values in MySQL using PHP

phpmysqlcountnumbers

提问by ?těpán Němejc

I have a MySQL database and in one column, I have numbers (price) and I need to count all numbers in this column with PHP... How can I do that?

我有一个 MySQL 数据库,在一个列中,我有数字(价格),我需要用PHP计算此列中的所有数字......我该怎么做?

回答by Prasannjit

If you want to count the number of columns use:

如果要计算列数,请使用:

Select count(column_name) FROM table name.

If you want the sum of column values then use:

如果您想要列值的总和,请使用:

Select SUM(column_name) FROM table name.

回答by steven

Or maybe SUM is what you really want:

或者也许 SUM 是您真正想要的:

Select SUM(column_name) FROM tablename

回答by Erman Belegu

UPDATE with PHP Code

使用 PHP 代码更新

If you want to count you can do it like this:

如果你想数数,你可以这样做:

    $query = "SELECT COUNT(*) FROM table_name"

    // Print out result
    while($row = mysql_fetch_array($result)){
    echo "Total count". $row['COUNT(*)'];
}

If you want to get the sum of one column, you can do like this:

如果你想得到一列的总和,你可以这样做:

$query = "SELECT SUM(column_name) FROM table_name"
// Print out result
    while($row = mysql_fetch_array($result)){
    echo "Total sum". $row['SUM(column_name)'];
}

回答by Rohan Kumar

Try mysqli_result()like,

尝试mysqli_result() 之类的,

<?php
    $mysqli = new mysqli("localhost", "my_user", "my_password", "world");

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    if ($result = $mysqli->query("SELECT COUNT(price) as total FROM tablename")) {

        /* Get field information for column 'SurfaceArea' */
        $finfo = $result->fetch_field_direct(1);
        printf("Total price:     %s\n", $finfo->total);
        $result->close();
    }
    /* close connection */
    $mysqli->close();
?>

回答by Kees Sonnema

You can use this for counting 1 row in your database:

您可以使用它来计算数据库中的 1 行:

<?php

$query = "SELECT COUNT(price) FROM yourtable ";

?>

Then you can use $queryin your code to show the results.

然后你可以$query在你的代码中使用来显示结果。

In mysql (phpmyadmin) you can just do:

在 mysql (phpmyadmin) 中,您可以执行以下操作:

SELECT COUNT(price) FROM yourtable