Jump to content

Problem with SQL MAX statement


cisclem

Recommended Posts

I am having a problem retrieving the MAX value of a field in a MySQL table and I am not sure I am doing it correctly. My code is as follows (I have removed the connection details for obvious reasons)...

 

$mysqli = mysqli_connect("", "", "", "");

$query = "SELECT MAX(ID) FROM stock";

$res = mysqli_query($mysqli, $query);

 

The field 'ID' an an auto-increment field in the table 'stock' and I want to display the number of the last record. Can you please confirm if my SQL statement is correct and how to assign the result of the query to a variable that can be displayed - thanks

Link to comment
https://forums.phpfreaks.com/topic/185492-problem-with-sql-max-statement/
Share on other sites

close

if you're not looking for the id of the last record you entered

$query="select MAX(ID) as MaxID from stock"; 

 

then you would just refer to MaxID

if you're looking for the id of the last record you entered

$query="select last_insert_id() as LastID from stock"; 

To answer the question:

 

$query="select last_insert_id() as LastID from stock"; 
$result = mysql_query($query) or trigger_error("Error in SQL: " . mysql_error());
$lastID = mysql_result($result, 0, 0);
echo $lastID;

 

Note that is how you obtain 1 field from the first row returned by the query, if you have multiple rows you want returned I would suggest looking into mysql_fetch_assoc (and notice the user comments for some usage).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.