PHP:获取mysql列中的最高和最低值? [英] PHP: get the highest and lowest value in a mysql column?
问题描述
我正在尝试获取 mysql 列中的最高和最低值,但我不知道这是否可能!
I'm trying to get the highest and lowest value in a mysql column but I hav eno idea if this is even possible!
我在官方 MYSQL 论坛中遇到了这段代码,但我真的不知道如何将这些值作为 PHP 变量获取!
I came across this code in the official MYSQL forum but I really don't know how to get those values as PHP variables!
SELECT
(SELECT `price` FROM mytable ORDER BY `price` LIMIT 1) AS lowest,
(SELECT `price` FROM mytable ORDER BY `price` DESC LIMIT 1) AS highest
所以基本上我需要做的是从那个 mysql 查询创建 PHP 变量,并获得最高值 $hiestprice
和最低值 $lowestprice
so basically what i need to do is to create PHP variables from that mysql quesry and to just get the highest value as $hiestprice
and the lowest as $lowestprice
所以我继续前进,我做到了:
so i went ahead and I did:
$sql = "SELECT
(SELECT `price` FROM mytable ORDER BY `price` LIMIT 1) AS lowest,
(SELECT `price` FROM mytable ORDER BY `price` DESC LIMIT 1) AS highest";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query ); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$hiestprice = $row['price'];
$lowestprice = $row['price'];
}
}
但这是错误的,当我回显 $hiestprice
和 $lowestprice
时,我的 PHP 页面上没有任何返回!
But that is wrong and I get nothing returned on my PHP page when I echo the $hiestprice
and $lowestprice
!
有人能指出我正确的方向吗?
Could someone please point me in the right direction ?
推荐答案
首先可以优化查询使用
SELECT MIN( `price` ) AS `lowest` , MAX( `price` ) AS `highest` FROM `mytable`
比你可以使用的价格
$highestprice = $row['highest'];
$lowestprice = $row['lowest']
这篇关于PHP:获取mysql列中的最高和最低值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!