简体   繁体   English

PDO查询返回空白数组

[英]PDO query returns blank Array

I am trying my hands on PDO for the first time. 我是第一次尝试PDO。 Issue is whenever I am running a PDO query I get a blank array in my browser 问题是,每当我运行PDO查询时,浏览器中都会出现一个空白数组

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. 打印或回显变量$ rows1,$ rows2和$ rows3的值时,会出现问题。

I should be getting pre formatted array but all I get is blank array, as shown 我应该获取预格式化的数组,但是我得到的只是空白数组,如图所示 问题

Let me know your inputs friends, thanks... 让我知道您的输入朋友,谢谢。

fetch method use something like a cursor to return the results. fetch方法使用类似游标的东西来返回结果。 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. 在上面的while循环中,当您在其下进行编码时,结果集的游标已经在末尾。 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. 只需检索结果,然后使用它们即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM