【发布时间】:2016-06-25 11:31:00
【问题描述】:
我是第一次尝试 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 和 $rows3 的值时会出现问题。
我应该得到预先格式化的数组,但我得到的只是空白数组,如图所示
朋友们请告诉我你的意见,谢谢...
【问题讨论】:
-
这些将不起作用,因为您已经使用了该结果集对象
-
您在 while 循环中获取数据,这就是 fetchAll 为空的原因。你需要不同的方法。先使用 fetchAll 将数据保存到变量中,然后在循环中使用该变量