Page 1 of 1
how do you select the last id in my sql table?
Posted: Sun Feb 08, 2009 7:30 am
by monsta-toast
hi what is the correct code for selecting the last row id in mysql table?
Code: Select all
$query="SELECT max(ID) FROM inventory ";
i tried this but it doesn't work

Re: how do you select the last id in my sql table?
Posted: Sun Feb 08, 2009 7:59 am
by Ziq
Do you have some errors?
Why are you using this query? If you want to insert data into database you should use the auto_increment attribute.
MySQL Manual
Re: how do you select the last id in my sql table?
Posted: Sun Feb 08, 2009 8:10 am
by monsta-toast
no i want to select the last id from the database so i can use the id as a unique file name for images.
Re: how do you select the last id in my sql table?
Posted: Sun Feb 08, 2009 9:42 am
by John Cartwright
monsta-toast wrote:hi what is the correct code for selecting the last row id in mysql table?
Code: Select all
$query="SELECT max(ID) FROM inventory ";
i tried this but it doesn't work

This will give you the highest ordered ID, so yes it does work. Please post the relevant code and errors describing why this doesn't work.
If you are inserting a row in the database and simply want it's ID back, you can use mysql_insert_id().
Re: how do you select the last id in my sql table?
Posted: Sun Feb 08, 2009 10:12 am
by monsta-toast
John Cartwright wrote:monsta-toast wrote:hi what is the correct code for selecting the last row id in mysql table?
Code: Select all
$query="SELECT max(ID) FROM inventory ";
i tried this but it doesn't work

This will give you the highest ordered ID, so yes it does work. Please post the relevant code and errors describing why this doesn't work.
If you are inserting a row in the database and simply want it's ID back, you can use mysql_insert_id().
This function returns 0 if the previous operation does not generate an AUTO_INCREMENT ID, or FALSE on MySQL connection failure. so how do i get the last id and add 1 to it? then use the id created as a file name?
Re: how do you select the last id in my sql table?
Posted: Sun Feb 08, 2009 11:08 am
by monsta-toast
anyone?

Re: how do you select the last id in my sql table?
Posted: Sun Feb 08, 2009 11:18 am
by John Cartwright
Are you asking how to execute the query?
Code: Select all
$query="SELECT max(ID) AS `maxid` FROM inventory ";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['maxid'];
Also, please do not bump your post within 24 hours of your last post.
Re: how do you select the last id in my sql table?
Posted: Sun Feb 08, 2009 11:26 am
by monsta-toast
Thanks A million!
Re: how do you select the last id in my sql table?
Posted: Sun Feb 08, 2009 12:24 pm
by abel
Code: Select all
$query="SELECT max(ID) FROM inventory limit 0,1";
right?
Re: how do you select the last id in my sql table?
Posted: Sun Feb 08, 2009 12:50 pm
by Kastor