简体   繁体   中英

Dynamic Database Driven CSS

Here is my problem, I have a site I am building. I am including an admin page to manage everything on the fly, that i have no issue with as it is pretty straight forward php, mysql etc. I have it in my head that i can use a database to store css and dynamically call it up as i add new setting for the different classes, id's etc. my table is this: settings id--class--div--setting

Where class is something like body, header, footer, etc. and div and setting are as follows:

.header {
$div:$setting;
}

in my script i am echoing the style tag and including this inside of the head tags.

my code for what it is worth is below:

$header_query = mysql_query("SELECT style, setting FROM styles WHERE class='header'");
$header_result = mysql_fetch_array($header_query);


echo "<style type='text/css'>";
echo ".header {";
   foreach($header_result as $hstyle => $hsetting){
   echo $hstyle.":".$hssetting.";";
   }

   echo "}";
   echo "</style>";

I figgured that would be enough to echo each setting for that particular class and I was right in part. Instead of echoing out the desired code my echo(depending on the mysql_fetch command i use) spits out something like this:

<style>
.header {
0:div;1:background;2:setting;3:url(x.jpg)
}
</style>

Any ideas, I'm stumped?

mysql_fetch_array fetches one row. So you may use something like

$header_query = mysql_query("SELECT style, setting FROM styles WHERE class='header'");

echo "<style type='text/css'>";
echo ".header {";

while($header_result_row = mysql_fetch_array($header_query,MYSQL_ASSOC))
    echo $header_result_row['style'].":".$header_result_row['setting'].";";

echo "}";
echo "</style>";

Almost all mysql_fetch_* are only affecting a single row, keep that in mind. See also the mysql_fetch_array examples .

That's correct, because the mysql_fetch_array returns an array (hence the name) that contains an indexed list of all results, where each row is an associative array.

Use

echo $hssetting['style'].":".$hssetting['setting'].";";

and you should be good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM