0

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

1

1 Answer 1

0

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, ';');
?>
Sign up to request clarification or add additional context in comments.

2 Comments

so, it is mean that only one theme can be inside the database (for example: theme color: blue)
Not necessarily, you can have the name of first table to be 'classic' instead of style, meaning it has the styles for classic theme. You can have another table named 'dark' which can have styles for the dark theme. Important note - all the theme tables should have the same column structure, otherwise things may break.

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.