通过从php中读取数据库中的值来更改css

问题描述 投票:-1回答:1

我想动态地改变我的CSS。我的css值应该来自数据库。我的数据库中有一个名为goalsorder表,它包含idgoal_1

这是我正在使用的代码:

<?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>

我想使标签<hr>的宽度动态。假设goal_1的值来自db 2。现在我的<hr>的宽度应该变成2px。为此,我使用的是style.php文件。

// 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;
}

任何帮助,将不胜感激。

php html css mysql database
1个回答
0
投票

尝试改变

.goal_1{
    width: <?php $width ?>px;
}

.goal_1{
    width: <?php echo $width; ?>px;
}

也可能

<h5><?php echo $width ?></h5>

<h5><?php echo $width; ?></h5>/* trailing semi-colon */

--

可能的解决办法并不意味着将数据库代码放在style.php中,而是使用会话变量,该变量可以填充在index.php中并在style.php中可用

所以,例如:

<?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;?>;
}

等等

© www.soinside.com 2019 - 2024. All rights reserved.