[英]MAX Value from SQL to PHP
How do I retrieve the max value of a column in SQL using PHP?如何使用 PHP 检索 SQL 中列的最大值?
Table name is pages
.表名是
pages
。
The code I have written into a function is:我写入 function 的代码是:
function max_from_page($column) {
global $db;
$sql = "SELECT MAX('" . $column . "')";
$sql.= "FROM pages";
$result = mysqli_query($db, $sql);
return $result;
}
UPDATE 1: I added an alias:更新1:我添加了一个别名:
function max_from_page($column) {
global $db;
$sql = "SELECT MAX(" . $column . ") AS maxsub";
$sql.= "FROM pages";
$result = mysqli_query($db, $sql);
return $result;
}
Then a var dump echo'ed bool(false)
然后一个 var dump echo'ed
bool(false)
UPDATE 2: So after adding a space before FROM
The var dump gives me this:更新 2:所以在
FROM
之前添加一个空格后,var dump 给了我这个:
object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) }
The max value I am expecting returned is 3
.我期望返回的最大值是
3
。 The above code executes absolutely fine on MYSQL command line.上面的代码在 MYSQL 命令行上执行得非常好。
You're using $result = mysqli_query($db, $sql);
您正在使用
$result = mysqli_query($db, $sql);
to return the result.返回结果。
mysqli_query
does return an mysqli-object
(if query has been sucsseful) but wont return the actual result of the query. mysqli_query
确实返回一个mysqli-object
(如果查询已成功),但不会返回查询的实际结果。
You should use你应该使用
$result = mysqli_fetch_assoc($result);
And then you would have $result['maxsub']
as the value you're looking for.然后您将拥有
$result['maxsub']
作为您要查找的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.