I'm storing basic CSS settings in a database so they can be configurable by a client using some sort of web form, then these can be echoed out within the style tag and override any existing settings. Basic settings like font family, background color, font color etc.
Table:

Rather than setting a column name for every css selector, I have decided to store settings like shown above as this would be easier to update and maintain.
I am trying to echo the "style_name" followed by "{", then every "style_value" then a closing tag "}". I'm nearly there, but I'm trying to figure out how to know when all style values associated with the style name have been echoed, then echo a closing tag, rather than after every value.
PHP Code:
$sql = 'SELECT style_name, style_value FROM style ORDER BY style_name';
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
$unique_css = array();
foreach ($results as $css) {
if (!in_array($css->style_name, $unique_css)) {
$unique_css[] = $css->style_name;
echo $css->style_name . " { " . $css->style_value;
} else {
echo $css->style_value;
}
echo '}';
}
Returns:
body {
background: #CCC; }
font-family: 'Verdana', sans-serif; }
font-size: 40px; }
text-align:center;
}
h1 {
font-size: 50px;
}
h2 {
font-family: 'Arial', sans-serif;
}
I understand that I could just echo every style name with value e.g.:
body { value1 } body {value2}
But I think that is just messy IMO. Help appreciated!
One of the best solutions is to use proper MySQL to group by the style names by using the GROUP_BY keyword and concatenating the style value string with GROUP_CONCAT:
SELECT style_name, GROUP_CONCAT(style_value SEPARATOR ' ') style_values FROM style GROUP BY style_name
This will result in:
STYLE_NAME STYLE_VALUES
body background: #CCC; font-family: 'Verdana', sans-serif; font-size: 40px; text-align: center;
h1 font-size: 50px;
h2 font-family: 'Arial', sans-serif;
Example fiddle:
More information about GROUP_BY and GROUP_CONCAT: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
After that you can put all styles together in a simple manner:
foreach ($results as $css) {
echo $css->style_name . " { " . $css->style_values + " }";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With