【发布时间】:2014-10-18 13:15:10
【问题描述】:
我是 PHP 的 PDO 新手,所以我想知道如何将数据分配给变量。
Array ( [0] => Array ( [id] => 1 [title] => Test Announcement! [link] => http://www.google.com ) ) 返回时我会收到它。
我希望它只是“测试公告”和“http://www.google.com”,并且能够将它们签署到 $title 和 $link 等变量。
functions.php
<?php
require("common.php");
function getAnnouncements() {
$query = "SELECT title, link FROM announcements";
try {
global $db;
// Execute the query against the database
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
print_r($result);
}
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("Error loading announcements");
}
}
?>
我使用了 kypros 的答案,现在我有了这个:
<?php
require("common.php");
function getAnnouncements() {
$query = "SELECT title, link FROM announcements";
try {
global $db;
// Execute the query against the database
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $announcement)
$title = $announcement['title'];
$link = $announcement['link'];
echo "<a href='".$link."'>".$title."</a>";
}
}
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("Error loading announcements");
}
}
?>
带有错误日志和空白页。
[18-Oct-2014 13:28:12 UTC] PHP Parse error: syntax error, unexpected '}', expecting T_CATCH in /home/dxbridge/public_html/scripts/functions.php on line 17
[18-Oct-2014 13:28:13 UTC] PHP Parse error: syntax error, unexpected '}', expecting T_CATCH in /home/dxbridge/public_html/scripts/functions.php on line 17
【问题讨论】:
-
对不起,我试着四处寻找。我去看看,谢谢。
-
Joel 没问题,我还添加了一个具体的答案,您可以参考以到达您想去的地方。 @MichaelBerkowski 这样做,如果他有很多公告,他只会得到第一个,而不是遍历所有公告。