PDA

Click to See Complete Forum and Search --> : Quick MySQL question


Kasracer
Feb 20th, 2005, 02:58 AM
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.

visualAd
Feb 20th, 2005, 03:07 AM
You can do it in SQL:

SELECT MAX(id) FROM tablename;

Kasracer
Feb 20th, 2005, 03:40 AM
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:

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

visualAd
Feb 20th, 2005, 05:21 AM
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:

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 */
}

Kasracer
Feb 20th, 2005, 10:16 PM
Thanks a lot.