我试图将我的旧脚本从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但无法让它工作。
答案 0 :(得分: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"];
?>
答案 1 :(得分: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'];
}