我正在构建一个网页,允许用户选择一个主题。我如何基于这个建议(我必须使用SESSION)构建它:
<link rel="stylesheet" type="text/css" href="<?php echo $_SESSION['style']?>" />
我试着在mysql数据库上创建一个名为'theme'
的表,像这样:
id | th_name | link
1 | blue | style.css
2 | back | black.css
3 | pink | pink.css
.................
和我的代码(不工作):
<?php
echo "<form>";
echo "<select>";
$sql = "select * from theme";
foreach ($dbh->query($sql) as $row)
{
?>
<option value="<?php $row['link'] ?>"><?php echo $row['th_name'] ?></option>
<?php
}
echo "</select>";
echo "</form>";
?>
第一个代码是关键。你有什么解决办法吗?(使用jquery或....?)
为什么要使用mysql数据库?你可以给一个变量同名的css文件。使用饼干。这是一个实现示例
只是要小心保护好它!
您可以按照上面展示的方式来做,但是出于安全考虑,您可能希望做得稍微不同(您的方式将为XSS提供很大的机会)。
本质上,您需要将$_SESSION
全局变量设置为具有该样式,并且该样式应该直接来自数据库。如果是我,我会这样做:
<?php
echo "<form>";
echo "<select name='"theme'" id='"select-theme'">";
$sql = "select * from theme";
foreach ($dbh->query($sql) as $row)
{
?>
<option value="<?php $row['id'] ?>"><?php echo $row['th_name'] ?></option>
<?php
}
echo "</select>";
echo "</form>";
?>
然后,在您的回发脚本中,这样做:
<?php
if (isset($_POST['theme']) {
// Perform query here to get the link's file, using PDO - watch out for XSS
// Note - you may have to call session_start()
// depending on your php.ini's settings
$_SESSION['style'] = $link;
}
如果你想用jQuery在飞行中做到这一点,你可以看到这里的信息:我如何使用jQuery切换我的CSS样式表?
此外,您可能希望像这样持久化您的更改:
<script type="text/javascript">
$("#select-theme").on("change", function() {
$.post({
url:'yoururl.php',
data: {
theme: $(this).find("option:selected").value()
});
});