0

我怎么能在我的页面顶部有我的数据库连接信息,但查询与代码分开但仍然相关,以便我可以打印或回显在我可以放置在我网站上的任何位置的 Div 中显示检索到的图像?

<?php
$db = new PDO('mysql:host=host;dbname=dbname;charset=UTF-8', 'username', 'password');
$q = "SELECT badge1 FROM user_badges WHERE username='{$_SESSION['username']}' LIMIT 1";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$badge1 = $row['badge1'];

if($badge1 == "unlocked") {
 print "image if user has unlocked the badge";
  } else {
 print "image if user hasn't unlocked the badge";
}

?>

我想将上述ifelse语句放在一个 div 中,这样我就可以将查询中打印的图像放置在我网站上的任何位置。这可能吗?

4

1 回答 1

1

有几种方法。这是一个例子:

<?php
$db = new PDO('mysql:host=host;dbname=dbname;charset=UTF-8', 'username', 'password');
$q = "SELECT badge1 FROM user_badges WHERE username='{$_SESSION['username']}' LIMIT 1";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$badge1 = $row['badge1'];
?> 

//Break out of PHP and add any HTML elements you want

<div id="whatever">

<?php
if($badge1 == "unlocked") {
    print "image if user has unlocked the badge";
} else {
    print "image if user hasn't unlocked the badge";
}
?>
</div>

ps 检查您的 PDO。混杂着旧MySQL_

于 2012-10-31T19:49:21.243 回答