Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the maximum value of a column in MySQL

Tags:

php

mysql

I want to select the maximum value of a column of my table. I'm using PHP and MySQL. This is what I have so far:

$max = "SELECT MAX(Id) FROM trialtabel2"; 
$max1 =  mysqli_query($dblink, $max); 
echo= $max1;

My debugger is just saying that it is a query returning a 0 boolean value (false). I cannot find a specific answer anywhere on the internet.

like image 230
Solomon Broadbent Avatar asked Jan 07 '23 02:01

Solomon Broadbent


1 Answers

You need to fetch the data from the mysqli_result object that was returned to you when you executed your query using mysqli_query.

    $max = "SELECT MAX(Id) as id FROM trialtabel2"; 
    $max1 =  mysqli_query($dblink, $max); 
    $row = mysqli_fetch_assoc($max1);    // this was missing
    $id=$row['id'];
    echo $id;

Note: I removed the loop because with MAX query without any grouping you will get only 1 row returned. If you had multiple rows in result set you would need to loop through all of them

like image 54
William Madede Avatar answered Jan 14 '23 11:01

William Madede