Php PDO查询返回空数组
我第一次尝试PDO。问题是,每当我运行PDO查询时,我的浏览器中就会出现一个空白数组 代码Php PDO查询返回空数组,php,pdo,Php,Pdo,我第一次尝试PDO。问题是,每当我运行PDO查询时,我的浏览器中就会出现一个空白数组 代码 <?php $config['db'] = array( 'host' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'website' ); $db = new PDO('mysql:host=' .$config['db']
<?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的值时出现问题
我应该得到预格式化的数组,但我得到的是空白数组,如图所示
让我知道你的输入,朋友们,谢谢…
fetch
方法使用类似光标的东西返回结果。因为您是从结果集的开始到结束(将光标从开始移动到结束)在
foreach($row in $rows){
// do something
}
//again access results below
echo '<pre>', print_r($rows, true), '</pre>';
然后根据需要循环结果
foreach($行中的行){
//做点什么
}
//再次访问下面的结果
回显“”,打印($rows,true),“”;
因此,我们的想法是不使用查询对象,因为它的本质是使用游标。只需检索结果,然后使用它们。
fetch
方法使用类似光标的东西返回结果。因为您是从结果集的开始到结束(将光标从开始移动到结束)在
foreach($row in $rows){
// do something
}
//again access results below
echo '<pre>', print_r($rows, true), '</pre>';
然后根据需要循环结果
foreach($行中的行){
//做点什么
}
//再次访问下面的结果
回显“”,打印($rows,true),“”;
因此,我们的想法是不使用查询对象,因为它的本质是使用游标。只需检索结果,然后使用它们。这些将不起作用,因为您已经使用了在while循环中获取数据的结果集object,这就是fetchAll为空的原因。你需要不同的方法。首先使用fetchAll将数据保存到变量中,然后在循环中使用此变量。这将不起作用,因为您已经使用了while循环中获取数据的结果集对象,这就是fetchAll为空的原因。你需要不同的方法。首先使用fetchAll将数据保存到变量中,然后在loopsdescription中使用此变量更好+10谢谢你的输入,伙计,有没有办法让fetch以某种方式重置?恐怕没有。链接是一些重置光标的问题。说明更好+10谢谢你的输入,伙计,有没有办法让fetch以某种方式重置?恐怕不行。这些链接是关于重置光标的问题
foreach($row in $rows){
// do something
}
//again access results below
echo '<pre>', print_r($rows, true), '</pre>';