Jump to content

Applying a class to the first and last MySQL record


chris9902

Recommended Posts

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";
}

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";
            }
}

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"?)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.