我第一次尝试使用PDO。问题是每当我运行PDO查询时,我在浏览器中得到一个空白数组
代码,
<?php
$config['db'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'website'
);
$db = new PDO('mysql:host=' .$config['db']['host']. ';dbname=' .$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
//$query returns PDO statment object
$query = $db->query('SELECT `articles`.`title` FROM `articles`');
print_r($query);
//we will use different methods on PDO to work with database
//a generic method to display all results
while($rows = $query->fetch(PDO::FETCH_ASSOC)){
echo '<br>'.$rows['title'];
}
$rows1 = $query->fetch(PDO::FETCH_ASSOC);
print_r($rows1);
$rows2 = $query->fetchAll(PDO::FETCH_ASSOC);
echo '<pre>', print_r($rows2, true), '</pre>';
$rows3 = $query->fetchAll(PDO::FETCH_NUM);
echo '<pre>',print_r($rows3, true),'</pre>';
$articles = $query->fetchAll(PDO::FETCH_ASSOC);
echo $articles[4]['title'];
?>
打印或回显变量$ rows1,$ rows2&amp;的值时出现问题。 $ rows3。
所示让我知道你的朋友,感谢...
答案 0 :(得分:3)
fetch
方法使用类似游标的方法来返回结果。因为您正在探索
while($rows = $query->fetch(PDO::FETCH_ASSOC)){
echo '<br>'.$rows['title'];
}
while循环上面,当你来到下面的代码时,结果集的光标已经在结尾了。因此,你得到一个空数组。
您必须先获取所有结果。
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
然后根据需要循环结果。
foreach($row in $rows){
// do something
}
//again access results below
echo '<pre>', print_r($rows, true), '</pre>';
因此,我们的想法是不使用查询对象,因为它使用游标的本质。只需检索结果,然后使用它们。