2014-10-18 71 views
0

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

對不起,我試圖尋找身邊。我會檢查一下,謝謝。 – 2014-10-18 13:19:00

+0

喬爾沒問題,我還加了一個具體的答案,以及你可以參考到你想要的地方。 @MichaelBerkowski這樣做,如果他有很多公告,他只會得到第一個,而不是循環所有的。 – Kypros 2014-10-18 13:25:13

回答

0

您的$result現在包含與您的select語句匹配的所有行。要訪問各個列值,你可以這樣做:

foreach($result as $announcement) 
{ 
    $title = $announcement['title']; 
    $link = $announcement['link']; 
    echo "<a href='".$link."'>".$title."</a>"; 
} 

這將輸出連接每個公告的鏈接並顯示超鏈接只是它的標題

+0

在OP中查找。編輯它新的錯誤。 – 2014-10-18 13:27:03

+0

對不起,我的錯。忘記用{}打開foreach循環。查看更新回答 – Kypros 2014-10-18 13:30:43

+0

呵呵,哈哈,我以爲我也檢查過了,:P – 2014-10-18 13:31:16