Oskar Lehtonen Oskar Lehtonen - 6 months ago 12
SQL Question

PHP IF inside <tr> <td> loop while looping results from MySQL database

I would need to display results in 3 rows and have same values under each other. Currently results are all going under each other. My code would have 3 IF sentences inside the loop.

My code is here:

echo "
<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" class=\"data\">
<tr>
<td class=\"dataHeader\"><h2>Vapaa</h2></td>
<td class=\"dataHeader\"><h2>Varattu</h2></td>
<td class=\"dataHeader\"><h2>Käyttö estetty</h2></td>
</tr>
";
while($result = mysql_fetch_array($sql)) {

echo "<tr>

if ($result[tila] == 'vapaa') {

<td>" . $result['id'] . " " . $result['tila']. "</td>

}

</tr>";

}

echo "</table>";

Answer

I think you don't want the if to be as text. So you have to do like this:

while($result = mysql_fetch_array($sql)) {

      echo "<tr> ";

      //First if
      if ($result[tila] == 'vapaa') {
            echo "<td>" . $result['id'] . " " . $result['tila']. "</td>";
      } else {
            echo '<td></td>';
      }

      //Second if
      if ($result[tila] == 'varattu') { 
            echo '<td>' , $result['id'] , ' ' , $result['tila']. '</td>';             
      } else {
            echo '<td></td>';
      }

      // Here you can add more ifs.

      echo  "</tr>";
  }

Because tables need to have the same number of cells (<td>) in a you need to add empty <td>s as describe above.

Comments