Skip to content
PHP Logo

How can PHP be used to dynamically change the color of text based on a specific value in a MySQL database?

To dynamically change the color of text based on a specific value in a MySQL database using PHP, you can retrieve the value from the database, and then use conditional statements to determine the color based on that value. You can then use inline CSS or HTML style attributes to apply the color to the text.

php
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve value from database
$sql = "SELECT color_value FROM table_name WHERE id = 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $color = $row["color_value"];
    }
}

// Determine color based on value
if ($color == "red") {
    $textColor = "red";
} elseif ($color == "blue") {
    $textColor = "blue";
} else {
    $textColor = "black";
}

// Apply color to text
echo "<p style='color: $textColor;'>Text with dynamically changing color</p>";

$conn->close();
?>