我是新来的这个PDO与PHP的东西,所以我想知道如何将数据分配给变量。PDO提取设置变量mysql php
当它返回时我得到这个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");
}
}
?>
随着error.log中和空白页。
[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
对不起,我试图寻找身边。我会检查一下,谢谢。 – 2014-10-18 13:19:00
乔尔没问题,我还加了一个具体的答案,以及你可以参考到你想要的地方。 @MichaelBerkowski这样做,如果他有很多公告,他只会得到第一个,而不是循环所有的。 – Kypros 2014-10-18 13:25:13