3

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

4
  • 1
    you are not updating the value of $previous Commented Mar 22, 2012 at 15:50
  • This has nothing to do with mysql, really, other than you're getting the data from the database. This is purely "how do I color alternating rows in a table". Commented Mar 22, 2012 at 15:50
  • @MarcB thanks that was useful to me -_- Commented Mar 22, 2012 at 15:56
  • Do not, I repeat, DO NOT, use the mysql_* interface. Switch to mysqli or PDO. It is deprecated and gone in the latest PHP release. Commented Jun 5, 2017 at 1:41

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.