I'm trying to make a Menu manager in PHP + SQL. My goal is to save every menu item and where it should link to in a seperate row. Every row has an internal identifier column called 'menu_id'.

I also want to add a function to be able to add a row. Therefore, I need to take the highest number available in 'menu_id' and add 1 (if highest is i.e. 24, new one should be 25). Sounds quite simple but I haven't managed to get this working yet, probably because I just started programming in general...

What I have now:

$query = "SELECT MAX(menu_id) FROM hostfx_menus";
$result = mysql_query($query);

while($row = mysql_fetch_array($result)){
	echo $row['MAX(menu_id)'];
}

This indeed outputs the highest number in menu_id. My problem is I still need to add '1' to this result and I have to put it in a form, which is already made up with HTML in a echo();.

Anybody who can help me with these last two points? Thank you very much in advance!

Recommended Answers

All 5 Replies

Use this to take the highest number:

$max=0;
foreach($menu_id as $id){
if($max<$id) $max=$id;
}
$max++;

Use this to take the highest number:

$max=0;
foreach($menu_id as $id){
if($max<$id) $max=$id;
}
$max++;

Thanks!

But could you please explain how I would be able to incorporate this with my query (and its results)?

$max=0;
while($row=mysql_fetch_array($result)){
if($max<$row['menu_id']) $max=$row['menu_id'];
}
$max++; //if doesn't work, try this: $max=$max*1+1;
$max=0;
while($row=mysql_fetch_array($result)){
if($max<$row['menu_id']) $max=$row['menu_id'];
}
$max++; //if doesn't work, try this: $max=$max*1+1;

Thanks again but they both didn't work out. Got it to work with some help from a friend though:

$query = "SELECT menu_id FROM hostfx_menus ORDER BY menu_id DESC";
$result = mysql_query($query);
$row = mysql_fetch_row($result);

$max = $row[0] + 1;

$max
Member Avatar for diafol

If the menu_id field is set to autoincrement you don't nedd to ascribe a specific value. When the new item is added you can retrieve it with mysql_insert_id().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.