0

I have little problem with connection style.php to db

<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
    header("Content-type: text/css; charset: UTF-8");
   $Color = "#000000";
   $Test = "#555000";
?>
#header {
   background-color: <?php echo $Test; ?>;
   width: 500px;
   height: 500px;
}
a{
    color: <?php echo $Color; ?>;
}

this code is working perfectly. and when i do something like this:

<?php
    header("Content-type: text/css; charset: UTF-8");
   $Color = "#000000";
   $Test = "#555000";
?>
#header {
   background-color: <?php echo $Test; ?>;
   width: 500px;
   height: 500px;
}
a{
    color: <?php echo $Color; ?>;
}

here #header{} this won't work but a{} will work. can i somehow make it work?

1
  • done any basic debugging, like hitting the url for both versions directly? It's possible that the db version is outputting something\ BEFORE the css stuff kicks in, so the generated output is foo#header, instead of just #header. Commented Oct 3, 2016 at 19:00

1 Answer 1

2

If you want generate CSS from PHP use it in .php file like this:

<html>
<body>
<?php
   $Color = "#000000";
   $Test = "#555000";
?>
<style>
#header {
   background-color: <?php echo $Test; ?>;
   width: 500px;
   height: 500px;
}
a{
    color: <?php echo $Color; ?>;
}
</style>
</body>
</html>

Do not use it in .css file. You can also generate new .css file from .php file with fopen() and fwrite() PHP functions and then just with meta tag include it into webpage.

Creating .css file from PHP

<?php
$Color = "#000000";
$Test = "#555000";
$css = '#header {
    background-color: '.$Test.';
    width: 500px;
    height: 500px;
}
a {
    color: '.$Color.';
}';

$myfile  = fopen("generated_style.css", "w") or die("Unable to open file!"); // Open file
fwrite($myfile, $css); // Write CSS
fclose($myfile); // Close file
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Hey dave, could you expand (provide a mini example of generating a css file) on your answer?
Edited answer @GovindRai

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.