I would like to store my css in mysql database. But how should I suppose to store it. And how to call it back to be displayed on html page.
Note: I just want to store css in mysql database only
I would like to store my css in mysql database. But how should I suppose to store it. And how to call it back to be displayed on html page.
Note: I just want to store css in mysql database only
I am not sure if storing CSS in database is a good idea, but since you are explicitly requesting for it then you might follow this approach.
TABLE: styles
| id | selector | style_name |
|----|----------|--------------|
| 1 | body | align-center |
| 2 | .d-flex | display-flex |
| 3 | #badge | custom-badge |
TABLE: styles_css
| id | style_name | property | value |
|----|--------------|--------------|-----------|
| 1 | align-center | text-align | center |
| 2 | display-flex | display | flex |
| 3 | custom-badge | color | red |
| 4 | custom-badge | font-size | 1.5rem |
Then when you need the styles for your HTML, you can join these tables to get CSS styles.
SELECT `property`, `value`
FROM `styles_css`
LEFT JOIN `styles`
ON `styles`.`style_name` = `styles_css`.`style_name`
WHERE
`styles`.`selector` = '#badge';
This will give you
| property | value |
|------------|----------|
| color | red |
| font-size | 1.5rem |
Example:
<?php
// prepare statement and bind params(PDO would be a good option)
$sql = "
SELECT `property`, `value`
FROM `styles_css`
LEFT JOIN `styles`
ON `styles`.`style_name` = `styles_css`.`style_name`
WHERE
`styles`.`selector` = '#badge';
";
//after execution, something like $styles = $db->exec($sql);
foreach($styles as $property => $value) {
$css = "{$property} : {$value}; ";
}
// remove trailing semi-colon
$css = rtrim($css, ';');
?>