doudang4568 2016-06-25 11:31
浏览 142
已采纳

PDO查询返回空白数组

I am trying my hands on PDO for the first time. Issue is whenever I am running a PDO query I get a blank array in my browser

The code,

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

The problem occurs while printing or echoing values for the variables $rows1, $rows2 & $rows3.

I should be getting pre formatted array but all I get is blank array, as shownIssue

Let me know your inputs friends, thanks...

  • 写回答

1条回答 默认 最新

  • drhwb470572 2016-06-25 11:41
    关注

    fetch method use something like a cursor to return the results. Since you are exploring from beginning to the end of the result set (moving cursor from the beginning to the end) inside the

    while($rows = $query->fetch(PDO::FETCH_ASSOC)){
        echo '<br>'.$rows['title'];
    }
    

    while loop above, when you come to code below that, the result set's cursor is already at the end. therefore, you get an empty array as result.

    You have to fetch all the results first.

    $rows = $query->fetchAll(PDO::FETCH_ASSOC);
    

    Then loop the results as you want.

    foreach($row in $rows){
        // do something
    }
    
    //again access results below
    echo '<pre>', print_r($rows, true), '</pre>';
    

    So the idea is to not to use the query object since its nature of using a cursor. Just retrieve the results, then use them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3