How can PHP be used to retrieve background color from a MySQL table for a webpage?
To retrieve background color from a MySQL table for a webpage using PHP, you can first query the database to fetch the color value, and then use that value to set the background color in the HTML output.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to fetch background color from MySQL table
$sql = "SELECT background_color FROM colors_table WHERE id = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
$background_color = $row["background_color"];
}
} else {
echo "0 results";
}
// Close MySQL connection
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>Background Color Example</title>
<style>
body {
background-color: <?php echo $background_color; ?>;
}
</style>
</head>
<body>
<h1>This is a webpage with a dynamic background color</h1>
</body>
</html>