php mysql echo | How to inherit colors from a subm

2020-05-08 07:34发布

问题:

I'm having some real trouble finding information on this topic and I would be very appreciative for any help. In short I have a form where users select a category from a drop down list, enter some contents, and hit submit which goes to SQL. Each category in the dropdown is color coded:

<option STYLE="color: #00CC66;" value="Option_1">Option_1</option>
<option STYLE="color: #0066CC;" value="Option_2">Option_2</option>
<option STYLE="color: #996633;" value="Option_3">Option_3</option>

etc

Then I have a php that pulls up the stored submitted data (categories and contents) into a table on that same page sorted by date.

<?php
$con=mysqli_connect("localhost","myuser","mypassword","mydb");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM mytable order by date DESC");

echo "<table border='1'>
<tr>
<th>Category</th>
<th>Contents</th>
<th>Date/Time</th>
</tr>";

while($row = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['category'] . "</td>";
  echo "<td>" . $row['contents'] . "</td>";
  echo "<td>" . $row['date'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysqli_close($con);
?> 

My question is, when echo places the information in the table, is there a way I can get 'category' showing up in the same colors as the user form? (IE, on the table, Option_1 would show up as #00CC66, Option 2 as 0066CC, etc...)

Basically I want the actual category text on the fetched table to display the same as it is in the drop down form. I don't mind if I need to manually set each one as the categories are limited, I just have no clue where to begin on this one. Appreciate any help in advance!

回答1:

Yes, but you would need to either change the value of the select box to the colour or manually do it like this:

function getColor($strOption)
{
   switch ($strOption)
   {
       case "Option_1":
       return "#00CC66";

       case "Option_2":
       return "#0066CC";
       #etc
    }
}

Then in your while loop:

while($row = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td><font color='".getColor($row['category'])."'> " . $row['category'] . "</font></td>";
  echo "<td>" . $row['contents'] . "</td>";
  echo "<td>" . $row['date'] . "</td>";
  echo "</tr>";
  }