-2

I want to ask how to set odd or event in mysql->php output. I can do this with that code:

if($i%2 == 0)
{
    $class = 'content';
}
else
{
    $class = 'contents';
}


echo "<tr class='$class'>...

...but if i remove manual a row in the mysql things at output get messed. I'm thinking some way with foreach...or something like that. Any help will be superb.

hakre
  • 193,403
  • 52
  • 435
  • 836
SZ4
  • 61
  • 2
  • 9
  • 1
    What is the question exactly? Please be more specific to your question. What did you tried? – John Skoumbourdis Oct 09 '12 at 22:06
  • 1
    Removing a database row won't mess with the table output. It will alternate between `content` and `contents` in the same way. Perhaps your question needs some clarification. Are you trying to alternate classes for presentational purposes, or is the odd/even alternation an inherent property of your data – Ben Graham Oct 09 '12 at 22:12
  • cancel, cat playing with kb again ... *sigh* – Cups Oct 09 '12 at 22:15
  • I'm trying to create custom odd/even. I dont want when i remove manual a row from mysql to be two tr with bgcolor: red and 1 (blue), i want to be red, blue, red, blue independently what is in my mysql. – SZ4 Oct 10 '12 at 10:11

2 Answers2

4

If you're trying to alternate on odd and even output lines, I like to use a simple toggle:

$toggle = false;
foreach($items as $item){

  if($toggle){
   ..contents...
  }else{
   ...alternative content....
  }
  $toggle = !$toggle;
}

You can compress this with a ternary comparison if compact code is desired

Ray
  • 40,256
  • 21
  • 101
  • 138
1

This will work:

$i = 0;
while ($row = $result->fetch_assoc()) {
    $class = ($i++ % 2) ? 'contents' : 'content';
...
}
Ross Smith II
  • 11,799
  • 1
  • 38
  • 43
  • This is cleaner code `BUT` it does not answer the OP's question... it just re-writes the code he has but leaves him with the same problem: `$i % 2` is not producing the results he wants. – Ben D Oct 09 '12 at 22:16
  • OK, then what *IS* the question, then? – Ross Smith II Oct 10 '12 at 01:55
  • The problem is that the OP is looping through a set of non-contiguous keys, so if the array looks like `array(0=>'a',1=>'b',2=>'c',4=>'d')` then using the *even-ness* of the key will result in the last two elements receiving the same class. Ray's answer is the correct workaround for this problem (though I agree that the OP's questions was poorly asked) – Ben D Oct 10 '12 at 06:30