我有一个页面,登录用户可以看到不同链接的列表,但前提是链接与MySQL数据库中的条目匹配,如下所示:
<li>
<?php
require ("scripts/connect.php");
$query = mysql_query("SELECT * FROM files WHERE subject='consulting' AND active='1'");
$numrows = mysql_num_rows($query);
if ($numrows > 0)
echo "
<a class='atags' href=\"javascript:showonlyone('consulting', this)\">Consulting</a>";
if ($numrows == 0)
echo "";
?>
</li>
<li>
<?php
require ("scripts/connect.php");
$query = mysql_query("SELECT * FROM files WHERE subject='Projects' AND active='1'");
$numrows = mysql_num_rows($query);
if ($numrows > 0)
echo "<li><a class='atags' href=\"javascript:showonlyone('projects', this)\">Projects</a></li>";
if ($numrows == 0)
echo "";
?>
</li>
... ETC
然而,我刚刚意识到如果我的session_start()中的$ username;在主持人字段中有1我希望显示不同的东西。我怎样才能做到这一点?从理论上讲,我所寻找的是这样的:
if ($username && $moderator == 1) {
echo "You can edit this.";
}
else
echo "<li>
<?php
require ("scripts/connect.php");
$query = mysql_query("SELECT * FROM files WHERE subject='art' AND active='1'");
$numrows = mysql_num_rows($query);
if ($numrows > 0)
echo "
<a class='atags' href=\"javascript:showonlyone('art', this)\">Art</a>";
if ($numrows == 0)
echo "";
?>
</li>
<li>
<?php
require ("scripts/connect.php");
$query = mysql_query("SELECT * FROM files WHERE subject='computer' AND active='1'");
$numrows = mysql_num_rows($query);
if ($numrows > 0)
echo "<li><a class='atags' href=\"javascript:showonlyone('computer', this)\">Computer</a></li>";
if ($numrows == 0)
echo "";
?>
</li>
<li>
<?php
require ("scripts/connect.php");
$query = mysql_query("SELECT * FROM files WHERE subject='critical reading' AND active='1'");
$numrows = mysql_num_rows($query);
if ($numrows > 0)
echo "<li><a class='atags' href=\"javascript:showonlyone('criticalreading', this)\">Critical Reading</a></li>";
if ($numrows == 0)
echo "";
?>
</li>
<li>
<?php
require ("scripts/connect.php");
$query = mysql_query("SELECT * FROM files WHERE subject='french' AND active='1'");
$numrows = mysql_num_rows($query);
if ($numrows > 0)
echo "<li><a class='atags' href=\"javascript:showonlyone('french', this)\">French</a></li>";
if ($numrows == 0)
echo "";
?>
</li>";
这可能吗?感谢。
答案 0 :(得分:3)
您可以在PHP和HTML代码之间自由切换。有时,对于控制流语句而不是大括号,使用替代冒号和结尾语法会有所帮助。
<?php if ($username && $moderator == 1): ?>
You can edit this.
<?php else: ?>
<li>
...
<?php
...
if ($numrows > 0):
?>
<a class='atags' href="javascript:showonlyone('art', this)">Art</a>
<?php
endif;
?>
<?php endif ?>
这比使用echo
容易得多,因为您不必更自然地转义引号和HTML读取。
答案 1 :(得分:1)
不是在echo语句中包含php标记,而是在实际打印之前处理数据库工作(设置要输出的所有变量)。
这样,您可以按照以下模式添加所需的任何信息:
// database stuff here
echo '...'
if ($moderator == 1) echo '...'
echo '...'
更好的选择是在MVC模式中处理所有这些。您可以在此处找到更多信息:http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller