获取每行的值

时间:2014-11-27 16:55:44

标签: php mysql

在我的mysql表中,我有一个包含值的行,我们可以调用此表" days"和#34;理发"。

所以我有5行所有" 1"," 2"," 3"," 4"," 5"在"理发"。我想要做的,在PHP中,将它们全部加在一起并回声。所以它可能看起来像这样:

echo "Total haircuts: ",$haircuts;

希望显示:

Total haircuts: 15
但是,我无法弄清楚如何。以下是我目前的做法。

$getstats = mysqli_query($con,"SELECT * FROM stats");
$gotstats = mysqli_fetch_array($getstats);
$haircuts = $gotstats['haircuts'];

但它只能回复"理发"第一排? :(

如果有可能的话,我有多个我想要的列和回声?

3 个答案:

答案 0 :(得分:1)

您可以在查询中使用MySQL语句SUM,只需更改您的代码:

$getstats = mysqli_query($con,"SELECT SUM(haircuts) AS totalhaircuts FROM stats");
$gotstats = mysqli_fetch_array($getstats);
$totalhaircuts = $gotstats['totalhaircuts'];
echo "Total haircuts: ",$totalhaircuts;

答案 1 :(得分:0)

您需要使用循环来获取所有行。例如:

$getstats = mysqli_query($con,"SELECT * FROM stats");
while($gotstats = mysqli_fetch_array($getstats)){
    $haircuts = $gotstats['haircuts']; 
    echo $haircuts . '<br />';
}

答案 2 :(得分:0)

您可能应该使用MySQL SUM()。

SELECT SUM(haircuts) as tot_cuts FROM stats;

$gotstats['tot_cuts'];