Php 如何从PDO语句回显结果数组
我有以下代码:Php 如何从PDO语句回显结果数组,php,mysql,pdo,Php,Mysql,Pdo,我有以下代码: $pages = $conn->prepare('SELECT * FROM pages WHERE slug = startpage'); $pages->execute(); $resultarray = array(); while($row = $pages->fetch(PDO::FETCH_ASSOC)){ $resultarray[] = $row; } 我之所以这么做是因为我
$pages = $conn->prepare('SELECT * FROM pages WHERE slug = startpage');
$pages->execute();
$resultarray = array();
while($row = $pages->fetch(PDO::FETCH_ASSOC)){
$resultarray[] = $row;
}
我之所以这么做是因为我想在整个文档中使用数组,而不仅仅是在while中。请参见以下示例:
//Somewhere outside of the while loop
<h1><?php echo $resultarray['header']?></h1>
//while循环之外的某个地方
最有效的方法是什么
/* instead of the 'while' loop you can use 'fetchAll' */
/* you can use 'while' if the values need to be processed */
$rows = $pages->fetchAll(PDO::FETCH_ASSOC);
/* the final variable will contain all rows */
echo $rows[0]['header'];
这里$i
是$resultarray
数组的索引。
这里的
$i
是$resultarray
数组的索引。不要忘记您有多维数组,因此对于第一行,您可以访问值:
$resultarray[0]['header']
不要忘记您有多维数组,因此对于第一行,您可以访问值:
$resultarray[0]['header']
啊,这就是为什么。如果您确定查询只返回一行,是否有办法绕过指定
[0]
的要求。。将代码更改为$resultarray=$row代码>然后您将能够访问像这样的值$resultarray['header']
啊,这就是为什么。如果您确定查询只返回一行,是否有办法绕过指定[0]
的要求。。将代码更改为$resultarray=$row
然后您将能够访问如下值$resultarray['header']
谢谢!谢谢你!