String comparison mysql, php

Is there a way to compare rows from two different tables in php? For example:

     Clothing Item      Price tag
     Scarf              £5
     Scarf              £6
     Scarf              £4
     Cloth              £10
     Shoe               £15

      

Basically I want to group different elements by their names. For every other element, I want to alternate two colors. So if this item is a scarf, I will dye it maybe blue, because the next item is also a scarf, I will also dye it blue. After that, since I have a rag, it will be colored yellow, but because the next one is a boot, it will be colored blue. I came up with something using php:

    $previous = "";
    while ($row = mysql_fetch_array($result)) 
    {
    if ( $row['firstName'] != $previous) {
    echo "<tr bgcolor = 'blue'>";
    }
    else {
    echo "<tr bgcolor = 'yellow'>";
    }
    blah blah
    }

      

When I do this, I don't get what I want. What I get from this is the first scarf is yellow and the other two are blue. Then, because the scarf! = Cloth, I get yellow, and also because the cloth! = Shoes, I become yellow, not blue.

I can see right away what the problem is, but I don't know how to fix it. Please help. Thanks to

+3


source to share


1 answer


Track the current color as a separate variable starting outside the loop, then change it when the element name changes:



$color = true;
$previous = '';
while ($row = mysql_fetch_array($result)) 
{
if ( $row['firstName'] != $previous) {
    $color = !$color;
    $previous = $row['firstName'];
}
echo "<tr bgcolor = '", ($color?'blue':'yellow'),"'>";


blah blah
}

      

+2


source







All Articles