我有一个MySQL数据库,在其中一列中,我有数字(价格),我需要使用PHP计算此列中的所有数字... 我该如何做?
如果您想要计算列数,请使用:
Select count(column_name) FROM table name.
如果您想要列值的总和,则使用:
Select SUM(column_name) FROM table name.
使用PHP代码进行UPDATE操作
如果您想进行计数,可以像这样执行:
$query = "SELECT COUNT(*) FROM table_name"
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total count". $row['COUNT(*)'];
}
如果你想要得到一列的总和,可以像这样操作:
$query = "SELECT SUM(column_name) FROM table_name"
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total sum". $row['SUM(column_name)'];
}
或者也许你真正想要的是SUM:
Select SUM(column_name) FROM tablename
<?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();
?>
<?php
$query = "SELECT COUNT(price) FROM yourtable ";
?>
$query
来显示结果。SELECT COUNT(price) FROM yourtable