PHP – MYSQL : sum() 操作
问题陈述:
在本文中,我们将使用PHP和 xampp 服务器对我们的数据库执行 sum() 聚合操作。
所以我们正在考虑 food_order 数据库并执行数据库 sum() 操作。
要求:
xampp
介绍:
PHP代表超文本预处理器,它是一种与数据库连接的服务器端脚本语言。
它与 MySQL 连接以在数据库中执行操作。
MySQL 是一种用于管理数据库的数据库查询语言。
- 和()
sum()函数是一种聚合操作,用于根据给定条件添加特定列。
句法:
SELECT SUM(column1),column2,...column1 from
table_name;
它也可以与 GROUP BY & HAVING 子句一起使用。
示例查询:
考虑下表:
查找食品的总成本
SELECT SUM(cost) from food;
输出:
Total cost: 2935
求食物的总重量
SELECT SUM(weight) from food;
Total weight: 382
查找与项目相关的食品项目的总成本
SELECT food_item, SUM(cost) FROM food GROUP BY food_item;
Total cakes = 1365
Total chocos = 200
Total chocoss = 705
Total fry = 345
Total milk = 320
方法
- 创建数据库
- 创建一个表
- 执行sum() 操作的PHP代码
脚步
- 启动 xampp 服务器
- 创建一个名为geek的数据库并创建一个名为food的表
表结构:
请参阅此处了解如何在 xampp 中插入记录
https://www.geeksforgeeks.org/performing-database-operations-in-xampp/
最后,食物表包含
- 执行求和函数的PHP代码
形式。 PHP
编写代码后键入“localhost/form. PHP”以在浏览器中查看输出。
PHP
"; echo "sum() aggregate Demo "; echo"";
echo "";echo " Find the total cost of food items ";echo "
";
//sql query
$sql = "SELECT SUM(cost) from food";
$result = $conn->query($sql);
//display data on web page
while($row = mysqli_fetch_array($result)){
echo " Total cost: ". $row['SUM(cost)'];
echo "
";
}
echo "";echo " Find the total weight of food items ";echo "
";
//sql query
$sql = "SELECT SUM(weight) from food";
$result = $conn->query($sql);
//display data on web page
while($row = mysqli_fetch_array($result)){
echo " Total weight: ". $row['SUM(weight)'];
echo "
";
}
//close the connection
$conn->close();
?>
PHP
"; echo "sum() aggregate with group by Demo "; echo"";
echo "";echo "
";echo "
";
//sql query
$sql = "SELECT food_item, SUM(cost) FROM food GROUP BY food_item";
$result = $conn->query($sql);
//display data on web page
while($row = mysqli_fetch_array($result)){
echo "Total ". $row['food_item']. " = ". $row['SUM(cost)'];
echo "
";
}
//close the connection
$conn->close();
?>
输出:
示例:sum() 和 group by 子句
形式1。 PHP
PHP
"; echo "sum() aggregate with group by Demo "; echo"";
echo "";echo "
";echo "
";
//sql query
$sql = "SELECT food_item, SUM(cost) FROM food GROUP BY food_item";
$result = $conn->query($sql);
//display data on web page
while($row = mysqli_fetch_array($result)){
echo "Total ". $row['food_item']. " = ". $row['SUM(cost)'];
echo "
";
}
//close the connection
$conn->close();
?>
输出: