PDO Fetch设置变量mysql php

时间:2014-10-18 13:15:10

标签: php html mysql pdo

我是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

1 个答案:

答案 0 :(得分:0)

您的$result现在包含与您的select语句匹配的所有行。要访问各个列值,您可以执行以下操作:

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

这将输出一个超链接,将每个公告链接到一个链接,并仅显示它的标题