[SOLVED] How to get the largest number from a MySQL database
Moderator: General Moderators
How to get the largest number from a MySQL database?
I have a table that have multiple columns. One of those columns is the Section ID column. In this column, the section ID start from 1, 2, 3, 4, 5 and so on. Can anyone show me a query that will give me the highst section ID from this column? For example, the Section IDs that I have are 1, 2, 3, 4, 5, 6, 7. What is the select query that will give me 7?
ljCharlie
ljCharlie
Code: Select all
select max(SectionID) from table_nameHere's what I tried:
It's not giving me the largest number. The query gave me nothing. However, when I run the query in phpMyAdmin, it does give me the correct value. What's going on with my code?
ljCharlie
Code: Select all
$query_SelectMax = "SELECT max(sectionID) FROM photoGallery";
$rsMAXID = mysql_query($query_SelectMax, $alumniConnection) or die(mysql_error());
$totalRows_rsMAXid = mysql_num_rows($rsMAXID);
if($totalRows_rsMAXid > 0){
//while($row_rsMAXid = mysql_fetch_assoc($rsMAXID)){
$row_rsMAXid = mysql_fetch_assoc($rsMAXID);
$sectionID = $row_rsMAXid["sectionID"];
$sectionID +=1;
echo "Section ID: ".$sectionID."<br>";
//}
}ljCharlie
-
jabbaonthedais
- Forum Contributor
- Posts: 127
- Joined: Wed Aug 18, 2004 12:08 pm
Line 7 is the problem line
That is because SQL has named the coulmn 'max(sectionID)' as you did not explicity give it a name.
If you want the column to have a more meaningful name, say LastId, then change the following 2 lines
Your code
You can be even cleverer than that and name the column NewId as follows, and it will have the newId in it
Hope this helps
change this toCode: Select all
$sectionID = $row_rsMAXid["sectionID"];
Code: Select all
$sectionID = $row_rsMAXid['max(sectionID)'];If you want the column to have a more meaningful name, say LastId, then change the following 2 lines
Your code
toCode: Select all
$query_SelectMax = "SELECT max(sectionID) FROM photoGallery";# . . . $sectionID = $row_rsMAXid["sectionID"];
Code: Select all
$query_SelectMax = "SELECT max(sectionID) as LastId FROM photoGallery";
.
.
.
$sectionID = $row_rsMAXid['LastId];Code: Select all
$query_SelectMax = "SELECT max(sectionID)+1 as NewId FROM photoGallery";
.
.
.
$sectionID = $row_rsMAXid['NewId];