【问题标题】:change css by reading a value from database in php通过从 php 中的数据库读取值来更改 css
【发布时间】:2018-03-03 10:23:25
【问题描述】:

我正在尝试动态更改我的 CSS。我的 css 值应该来自数据库。我的数据库中有一个名为ordergoals 表,它包含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>

我想让标签&lt;hr&gt; 的宽度动态化。假设goal_1 的值来自db 2。现在我的&lt;hr&gt; 的宽度应该变成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】:

尝试改变

.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 */

--

不意味着将 db 代码放入 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;?>;
}

【讨论】:

  • 也许我也应该在 style.php 文件中导入我的数据库?
  • 如果您在浏览器中查看style.php 的来源,它看起来是否正确?
  • 自己试过了——应该记得它不会像这样工作。将数据库代码放在style.php 中应该可以工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多