【问题标题】:PDO query returns blank ArrayPDO 查询返回空白数组
【发布时间】: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 将数据保存到变量中,然后在循环中使用该变量

标签: php pdo


【解决方案1】:

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>';

所以这个想法是不要使用查询对象,因为它使用游标的性质。只需检索结果,然后使用它们。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-29
  • 2023-04-03
  • 2014-02-02
  • 2016-03-24
相关资源
最近更新 更多