user3625283
user3625283

Reputation: 17

Changing background color of a php table

I have the following code:

while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
    echo "<td id='col1'>" . $row['inputId'] . "</td> <td id='col2'>" . $row['inputReqDate'] . "</td> <td id='col3'>" . $row['inputOrderDate'] . "</td> <td id='col4'>" . $row['inputPriority'] . "</td><td id='col5'>" . $row['inputDescription'] . "</td>" ;
  echo "</tr>";
}

I need to make it so when col4 contains the text "priority" it changes the background color for the whole row. How would I go about doing this?

ps. Sorry I have not attempted any javascript, I am new to the language!

Upvotes: 0

Views: 65

Answers (3)

Nathaniel Wendt
Nathaniel Wendt

Reputation: 1202

You could check the value, and given a match, add a css class to the row that could be styled.

while($row = mysqli_fetch_array($result)) {
  //New portion
  if($row['inputPriority'] == "priority"){
    echo "<tr class='priority'>";
  } else {
    echo "<tr>";
  }
  echo "<td id='col1'>" . $row['inputId'] . "</td> <td id='col2'>" . $row['inputReqDate'] . "</td> <td id='col3'>" . $row['inputOrderDate'] . "</td>";
  echo "<td id='col4'>" . $row['inputPriority'] . "</td><td id='col5'>" . $row['inputDescription'] . "</td>" ;
  echo "</tr>";
}

Also, I'm guessing that you will have multiple columns labeled with id col1, col2, etc. Id's are meant to be unique on the page, you should refactor to make these attributes as classes.

For example:

<td class='col1'>

Upvotes: 0

Ricardo Nu&#241;ez
Ricardo Nu&#241;ez

Reputation: 989

You can just add it to the TR.

css:

.priority { background: red; }

PHP:

while($row = mysqli_fetch_array($result)) {
  echo "<tr  class='" . $row['inputPriority'] . "' >";
    echo "<td id='col1'>" . $row['inputId'] . "</td> <td id='col2'>" . $row['inputReqDate'] . "</td> <td id='col3'>" . $row['inputOrderDate'] . "</td> <td id='col4'>" . $row['inputPriority'] . "</td><td id='col5'>" . $row['inputDescription'] . "</td>" ;
  echo "</tr>";
}

Upvotes: 0

Cineris
Cineris

Reputation: 581

Why not just change your php to add the class to the row for you?

while($row = mysqli_fetch_array($result)) {
  echo "<tr" . ($row['inputPriority'] == 'Priority' ? ' class="priority"': '') . ">";

  echo "<td id='col1'>" . $row['inputId'] . "</td> <td id='col2'>" . $row['inputReqDate'] . "</td> <td id='col3'>" . $row['inputOrderDate'] . "</td> <td id='col4'>" . $row['inputPriority'] . "</td><td id='col5'>" . $row['inputDescription'] . "</td>" ;
  echo "</tr>";
}

Then you can just add the css for the row:

tr.priority {
  background-color: red;
}

Upvotes: 1

Related Questions