2014-10-18 63 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