我正在尝试这样做,以便在标题链接中显示最新公告。 我已经尝试过这样做了,现在我只是试图让它甚至返回变量而且它不会...
的functions.php
<?php
require("common.php");
function getAnnouncements() {
$query = "SELECT * FROM announcements";
try {
global $db;
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute();
echo $result['title'];
}
catch(PDOException $ex) {
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
}
?>
的index.php
<div class="announcement">
<div class="container">
Latest Announcements: <?php getAnnouncements(); echo "<a href=''></a>" ?>
</div>
</div>
是的,我将文件包含在顶部,并且没有拼写错误。
答案 0 :(得分:1)
首先,确保$db
初始化为:
$db = new PDO("mysql:host=[host here];dbname=[dbname]e;charset=utf8",[username],[password]);
你想要获取一个关联数组并像这样循环:
$result = $result->fetchAll(PDO::FETCH_ASSOC);
for($result as $a_result)
echo '<a href="'.$a_result['link'].'">'.$a_result['title'].'</a>';
这假设数据库中有link
列