Ester
Ester

Reputation: 133

comparing rows mysql, php

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

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

I basically want to group the different items by their names. For each different item, I want to alternate between two colours. So if the item is a scarf, I will colour it maybe blue then because the next item is also a scarf, I will colour it blue as well. After that since I have a cloth, it will be coloured yellow and because the next one is a shoe, it will be coloured 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 would get from this is the first scarf is yellow, while the other two are blue. Then because scarf != cloth, I get a yellow and also because cloth != shoe, I get yellow instead of a blue.

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

Upvotes: 3

Views: 2672

Answers (1)

Scott Keck-Warren
Scott Keck-Warren

Reputation: 1952

Keep track of the current color as a separate variable starting outside the loop and then change it when the item's first 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
}

Upvotes: 2

Related Questions