我是新來的這個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