0

我正在尝试将我的旧脚本从 MYSQL 转换为 PDO,尽管遇到了一个小问题。由于某种原因,我无法获取多个结果。[很可能我的代码是错误的]

原来的

 <?php

                    $site_pages = mysql_query("SELECT * FROM pages WHERE show_nav = '1' ORDER BY `display_nav` ASC");
                    if(mysql_num_rows($site_pages) == 0){
                        echo '';
                    }else{

                        while($n = mysql_fetch_array($site_pages)){
                            $title = $n["title"];
                            $shortname = $n["shortname"];

                            echo '<li><a href="?p='.$shortname.'" class="nav"> '.$title.' </a></li>


                    ';
                        }

                    }
                    ?>

我的尝试:

    <?php

$STH - $DBH -> prepare( "SELECT * FROM pages WHERE show_nav = '1' ORDER BY `display_nav` ASC" );

$STH -> execute();
$result = $STH -> fetch();
echo $result ["title"];

?>

我研究了 PDO fetch 但无法使其正常工作。

4

2 回答 2

0

我建议你使用PDOStatement::fetchAll.

所以,你会这样使用它:

<?php

    $STH = $DBH -> prepare( "SELECT * FROM pages WHERE show_nav = '1' ORDER BY `display_nav` ASC" );

    $STH -> execute();
    $result = $STH -> fetchAll(PDO::FETCH_ASSOC);
    echo $result [0] ["title"];

?>
于 2013-11-07T06:17:58.730 回答
0

或者,也许您正在寻找这个:

$sth = $dbh->prepare('SELECT * FROM pages WHERE show_nav="1" ORDER BY display_nav ASC');
$sth->execute();

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    echo $row['title'];
}
于 2013-11-07T06:35:53.617 回答