Jump to content

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).

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.