通过从php中读取数据库中的值来更改css
问题描述:
I am trying to change my css dynamically. My css value should come from a database. I have a goals
table in my database named order
and it contains id
and goal_1
.
Here is the code I'm using:
<?php
$conn = mysqli_connect('localhost','root','','order');
$query1 = "SELECT * FROM `goals`";
$result = mysqli_query($conn, $query1);
while ($row = mysqli_fetch_array($result)) {
$width = $row["goal_1"]; `// storing value in a variable from db.`
}
?>
<!DOCTYPE html>
<html>
<head>
<title>project-1</title>
<link rel="stylesheet" type="text/css" href="style.php">
</head>
<body class="container">
<div>
<h4>Goal_1</h4>
<h5><?php echo $width ?></h5> // this value is supposed to came from db.
<hr align="left" class="goal goal_1">
</div>
</body>
</html>
I want to make the width of tag <hr>
dynamic. Suppose the value of goal_1
came from db 2
. Now the width of my <hr>
should become 2px
. For this purpose, I am using a style.php
file.
// my css file
<?php
header('Content-Type: text/css');
?>
.container {
width: 1170px;
margin: 0 auto;
}
div{
float: left;
width: 330px;
margin-top: 20px;
}
.goal{
height:15px;
background-color:#32CD32;
}
.goal_1{
width: <?php $width ?>px; `// i am trying to do this to take the value form my db. but its not working`
}
h4{
margin-bottom: 20px;
}
h5{
float: left;
margin-left: 35px;
margin-right: 20px;
}
Any help would be appreciated.
答
try changing
.goal_1{
width: <?php $width ?>px;
}
to
.goal_1{
width: <?php echo $width; ?>px;
}
and also possibly
<h5><?php echo $width ?></h5>
to
<h5><?php echo $width; ?></h5>/* trailing semi-colon */
--
A possible work-around that does not mean putting the db code inside style.php
would be to use a session variable which can be populated in index.php
and made available within style.php
So, for example:
<?php
/* index.php */
session_start();
$_SESSION['style']=(object)array(
'h1' => (object)array('color'=>'red','font-size'=>'1.25rem'),
'hr' => (object)array('width'=>'500px'),
);
?>
<html>
<head>
<title>Dynamic styles</title>
<link rel='stylesheet' href='style.php' />
</head>
<body>
<h1>Dynamic style</h1>
<hr />
</body>
</html>
<?php
/* style.php */
session_start();
if( !empty( $_SESSION['style'] ) ){
$obj=$_SESSION['style'];
$h1=$obj->h1;
$hr=$obj->hr;
}
?>
h1{
color:<?php echo $h1->color; ?>;
font-size:<?php echo $h1->{'font-size'}; ?>
}
hr{
width:<?php echo $hr->width;?>;
}
etc