Home > Software design >  How do I use inline CSS in PHP from a database
How do I use inline CSS in PHP from a database

Time:10-03

I am making a website that people can post articles to and I want the user to be able to pick the background color and font color but I can't use the inline CSS for the colors because the double quotes ended before the hex code.

<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "bulletin_board";

//Create connection
$connection = new mysqli($host, $username, $password, $dbname);

//Check connection
if ($connection->connect_error) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, title, content, bg_color FROM cards";
$result = $connection->query($sql);

if ($result->num_rows > 0) {
//data output of each row
    while ($row = $result->fetch_assoc()) {
        echo "<div class=card style=background-color: " . $row["bg_color"] . "><h2>" . $row["title"] . "</h2>" . "<p>" . $row["content"]. "</p>" . "</div>";
            }
    } else {
        echo "0 results";
    }
?>

How can I make it so that the hex color code shows inside the quotes?

Chrome showing the problem

CodePudding user response:

So you use a mixture of single and double quotes so that the inner quotations do not prematurely terminate the outer quotes.

    echo "<div class='card' style='background-color: " . $row["bg_color"] . "'>
            <h2>" . $row["title"] . "</h2>" . 
            "<p>" . $row["content"]. "</p>" . 
        "</div>";
}

Or to help make it more readable and maintainable

    echo "<div class='card' style='background-color:$row[bg_color]'>
            <h2>$row[title]</h2>
            <p>$row[content]</p> 
        </div>";
}
  • Related