Solomon Broadbent
Solomon Broadbent

Reputation: 303

How to select the maximum value of a column in 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.

Upvotes: 4

Views: 5102

Answers (4)

Fisherman
Fisherman

Reputation: 6121

two ways first is as people described

$max = "SELECT MAX(Id) as max_id FROM trialtabel2";     
$max1 =  mysqli_query($dblink, $max);   
$row = mysqli_fetch_assoc($max1); 
$max_id=$row['max_id'];      
echo $max_id;  

second is ordering and limiting

$max_id = 0;
$max = "SELECT id  FROM trialtabel2 order by id desc limit 0,1";    
$max1 =  mysqli_query($dblink, $max);     
while($row = mysqli_fetch_assoc($max1)){    
   $max_id=$row['id'];    
}    
echo $max_id;  

In Your code you missing the fetch statement. you need to fetch from the resultset. see above what you are missing.

Upvotes: 4

William Madede
William Madede

Reputation: 723

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

Upvotes: 5

Krishna Gupta
Krishna Gupta

Reputation: 685

$max = "SELECT Id FROM trialtabel2 order by id desc limit 1"; 
$max1 =  mysqli_query($dblink, $max); 
$result = mysqli_fetch_assoc($max1);
pre($result);

Upvotes: -2

Ajay Makwana
Ajay Makwana

Reputation: 2372

Try using this..,

$max = "SELECT MAX(Id) as maxId FROM trialtabel2"; 
$max1 =  mysqli_query($dblink, $max); 
$row = mysqli_fetch_assoc($max1);
echo $row['maxId'];

Hope this helps..

Upvotes: 2

Related Questions