|
-
Feb 20th, 2005, 03:58 AM
#1
Quick MySQL question
I have a column in one of my tables that has ID numbers. How can I find out what the highest ID number is that the table holds? I thought of just counting but eventually, as entries are deleted, the highest ID will end up being higher than counting each entry.
Last edited by Kasracer; Feb 20th, 2005 at 11:16 PM.
-
Feb 20th, 2005, 04:07 AM
#2
Re: Quick MySQL question
You can do it in SQL:
Code:
SELECT MAX(id) FROM tablename;
-
Feb 20th, 2005, 04:40 AM
#3
Re: Quick MySQL question
Thanks
Last question, I promiss. I'm writing a function that returns the highest ID. How would I do so without wasting resources? Right now I have it so it does this:
PHP Code:
function upperbound()
{
connect();
$result = mysql_query("SELECT MAX(number) FROM blogs");
if (!$result) {
die('Invalid query: ' . mysql_error());}
$row = mysql_fetch_assoc($result);
return $row['id'];
}
That has to be inefficient but I don't
Appended: Actually, it doesn't look like it works correctly. Ugh, I hate being stupid
-
Feb 20th, 2005, 06:21 AM
#4
Re: Quick MySQL question
Your function is efficient enough. The only change I would suggest making is to use the mysql_fetch_row() function instead of the mysql_fetch_assoc(). Fetch row simply loads each column into a number indexed array, whereas, fetch_assoc has to make an associative array with the column names as indexes.
As fetch_assoc has the column names as indexes, in your query the column name will default to MAX(number) therefore you will have to access it in the associative array using $row['MAX(number)']. You can give the column an alias name in the SQL like this:
SELECT MAX(number) id FROM blogs;
Your function will then work.
But like I suggested above, the most efficient way of doing this is to use the mysql_fetch_row() function instead:
PHP Code:
function upperbound()
{
connect();
$result = mysql_query("SELECT MAX(number) FROM blogs");
if (!$result) {
die('Invalid query: ' . mysql_error());}
$row = mysql_fetch_row($result);
return (int) $row[0]; /* cast to an integer - incase of no rows in DB */
}
-
Feb 20th, 2005, 11:16 PM
#5
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|