Home > other >  How do I style specific words when it gets fetched from my MySQLI database in PHP
How do I style specific words when it gets fetched from my MySQLI database in PHP

Time:07-28

I have data being fetched from MySQLI database. I want to style "Small" so it looks like this: enter image description here

Here is what my table looks like in PHP. I am unsure how to style specific words from fetched data.

enter image description here

Here's my PHP code:

    <?php

    $connect = mysqli_connect( 'placeholder','placeholder','placeholder','placeholder');
    $sql = "SELECT * FROM databasename";
    $result = $connect->query($sql);

    if ($result->num_rows > 0) {
        while ($row = $result-> fetch_assoc()) {
            echo "<tr><td>" . $row["item_name"] . "</td>
                      <td>" . $row["item_cooldown"] . "</td>
                      <td>" . $row["item_effect"] . "</td>
                      <td>" . $row["item_passive"] . "</td>
                      <td>" . $row["item_cost"] . "</td>
                      <td>" . $row["item_type"] . "</td> 
                      <td>" . $row["item_size"] . "</td></tr>";
        }
    } 
    else {
        echo "No Results";
    }
    $connect->close();
    ?>

</table>

Any help is very appreciated.

CodePudding user response:

to your last <td> tag change it to:

<td style='backgroundColor:green'> ...

CodePudding user response:

Add a span inside the related cell (the last td tag pair) and make a css class to style it.

You could even have different colours for different data if you make a base class and a modifier class that is either applied using if/else or switch, or just use the data as the class name if they're single-word.


Completely untested, but shouldn't be too far off. I used single quotes to not conflict with the double quotes of the html syntax. My PHP might be a bit rusty.

'<td>
  <span >' . $row['item_size'] . '</span>
</td>'

CSS

.sizetag {
  border-radius 3px
  padding: .5em
}

.large {
  background-color: green
}

Then supply with the classes you need and adjust the colours until they are nice and the text is stil readable.

If you don't want to use the data name as a class you could do the following which uses colour name (or whatever you need) instead.

I would place this inside the while:

$color = ""

switch ($row['item_size']) {
  small:
    $color = 'bg-green';
    break;
  medium:
    $color = 'bg-red';
    break;
  large:
    $color = 'bg-yellow';
    break;
}

And this to replace the last td

'<td>
  <span >' . $row['item_size'] . '</span>
</td>'

And again supply with the classes you need and adjust the colours until they are nice and the text is stil readable.

  • Related