chris9902 Posted May 17, 2007 Share Posted May 17, 2007 probably very simple but I need to apply a class to the first and last records from a MySQL query. What I'm trying to do is pull the menus for my site but the first and last links need a class name for the design. I can't set them in the database because the order and items in the menu will change from time to time. so, here is how I pull my menu (cut down for this post). You can see it just grabs the name, url and makes a link. How would I apply a class to the first and last records? mysql_connect("localhost","root","password"); mysql_select_db("my_site"); $result = mysql_query("SELECT * FROM menu ORDER BY id"); while ($are=mysql_fetch_array($result)) { $name = $are['name']; $url = $are['url']; print '<a href="'.$url.'">'.$name.'</a>'."\n"; } Link to comment https://forums.phpfreaks.com/topic/51786-applying-a-class-to-the-first-and-last-mysql-record/ Share on other sites More sharing options...
jitesh Posted May 17, 2007 Share Posted May 17, 2007 mysql_connect("localhost","root","password"); mysql_select_db("my_site"); $result = mysql_query("SELECT * FROM menu ORDER BY id"); $values_to_color = array(); $values_to_color[0] = mysql_result($result,0,'Primary Key(id)'); $values_to_color[1] = mysql_result($result,mysql_num_rows($result)-1,'Primary Key(id)'); while ($are=mysql_fetch_array($result)) { $name = $are['name']; $url = $are['url']; if(in_array($are['id'],$values_to_color)){ print '<a href="'.$url.'" class="color">'.$name.'</a>'."\n"; }else{ print '<a href="'.$url.'">'.$name.'</a>'."\n"; } } Link to comment https://forums.phpfreaks.com/topic/51786-applying-a-class-to-the-first-and-last-mysql-record/#findComment-255165 Share on other sites More sharing options...
chris9902 Posted May 17, 2007 Author Share Posted May 17, 2007 Thanks for the help. You pointed me in the right direction. I was looking for "mysql_num_rows" but couldn't remember how to count the rows (been a while since I've used PHP) I also needed IDs not classes (my mistake) so they have to be unique. Anyway here is my final code. works just as I wanted. $count = 1; $total = mysql_num_rows($result); while ($are=mysql_fetch_array($result)) { $name = $are['name']; $url = $are['url']; if ($count == 1) { print '<li><a href="'.$url.'" id="left">'.$name.'</a></li>'."\n"; } elseif ($count == $total) { print '<li><a href="'.$url.'" id="right">'.$name.'</a></li>'."\n"; } else { print '<li><a href="'.$url.'">'.$name.'</a></li>'."\n"; } $count++; } Thanks again for the quick reply. (why does this forums change the letter next to e on the keyboard to "are"?) Link to comment https://forums.phpfreaks.com/topic/51786-applying-a-class-to-the-first-and-last-mysql-record/#findComment-255175 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.