You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改PHP代码输出员工表最高与最低薪资的纯数值?

获取员工表最高/最低薪资的纯数值输出解决方案

Hey there! I see you're trying to get just the raw salary values instead of the array output from print_r()—let's sort this out quickly.

问题根源

Your current query uses aggregate functions (MAX() and MIN()) which return a single row of results. The fetch_assoc() method gives you an associative array where the keys are the column names (or function calls, in your case) and the values are the salaries you want. print_r() just dumps the whole array structure, which isn't what you need.

两种修改方案

方案1:给聚合结果起别名(推荐,更易读)

First, update your SQL to assign clear aliases to the MAX/MIN values. This makes accessing the array keys much cleaner:

<?php
include_once('db.php');
// 给MAX和MIN结果添加别名,让数组键更直观
$sql = "SELECT MAX(salary) AS max_salary, MIN(salary) AS min_salary FROM employees"; 
$query = $conn->query($sql);

// 因为聚合查询只返回一行结果,不需要while循环
$row = $query->fetch_assoc();

// 直接访问数组键来输出纯数值
echo "最高薪资:" . $row['max_salary'];
echo "<br>";
echo "最低薪资:" . $row['min_salary'];
?>

方案2:直接使用默认列名(不推荐,可读性差)

If you don't want to change the SQL, you can access the values using the function names as the array keys (but this is less clean):

<?php
include_once('db.php');
$sql = "SELECT MAX(salary), MIN(salary) FROM employees";
$query = $conn->query($sql);
$row = $query->fetch_assoc();

echo "最高薪资:" . $row['MAX(salary)'];
echo "<br>";
echo "最低薪资:" . $row['MIN(salary)'];
?>

额外提示

You don't need the while loop here because aggregate functions like MAX() and MIN() always return exactly one row of results for the entire table. Using while would only make sense if you were grouping results (e.g., by department).

内容的提问来源于stack exchange,提问作者Deepak Shukla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:30:19