简体   繁体   中英

MAX Value from SQL to PHP

How do I retrieve the max value of a column in SQL using PHP?

Table name is pages .

The code I have written into a function is:

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:

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)

UPDATE 2: So after adding a space before FROM The var dump gives me this:

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 . The above code executes absolutely fine on MYSQL command line.

You're using $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.

You should use

$result = mysqli_fetch_assoc($result); 

And then you would have $result['maxsub'] as the value you're looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM