为什么print_r()能查询出数据来为什么加上键名就查不出来了?

WBOY
Release: 2016-06-06 20:20:15
Original
928 people have browsed it

最后一行这样print_r($res2);可以查询出数据来 为什么加上键名就会报错了?
print_r($res2['name']);
提示这个错误
Notice: Undefined index: name in D:\wamp\www\fenyechaxun.php on line 16

这是数据库的内容
为什么print_r()能查询出数据来为什么加上键名就查不出来了?

<code><?php header('content-type:text/html;charset=utf-8;');
 $pdo=new PDO("mysql:host=localhost;dbname=t1","root","");
 $stmt=$pdo->prepare("select * from test");
 $stmt->execute();
 $res=$stmt->fetchall();
 $rows=count($res);
 $pagesize=3;
 $pagenum=ceil($rows/$pagesize);
 $page=empty($_GET['page'])?1:$_GET['page']; 
 $startnum = ($page - 1)*$pagesize;
 $query = "SELECT * FROM test LIMIT $startnum,$pagesize";
 $stmt2=$pdo->prepare($query);
 $stmt2->execute();
 $res2=$stmt2->fetchall();
 print_r($res2['name']);
?></code>
Copy after login
Copy after login

回复内容:

最后一行这样print_r($res2);可以查询出数据来 为什么加上键名就会报错了?
print_r($res2['name']);
提示这个错误
Notice: Undefined index: name in D:\wamp\www\fenyechaxun.php on line 16

这是数据库的内容
为什么print_r()能查询出数据来为什么加上键名就查不出来了?

<code><?php header('content-type:text/html;charset=utf-8;');
 $pdo=new PDO("mysql:host=localhost;dbname=t1","root","");
 $stmt=$pdo->prepare("select * from test");
 $stmt->execute();
 $res=$stmt->fetchall();
 $rows=count($res);
 $pagesize=3;
 $pagenum=ceil($rows/$pagesize);
 $page=empty($_GET['page'])?1:$_GET['page']; 
 $startnum = ($page - 1)*$pagesize;
 $query = "SELECT * FROM test LIMIT $startnum,$pagesize";
 $stmt2=$pdo->prepare($query);
 $stmt2->execute();
 $res2=$stmt2->fetchall();
 print_r($res2['name']);
?></code>
Copy after login
Copy after login

从你的截图可以看出~你查询出来的数组应该是这样子的:

<code>array(
0=>[
'type'=>1,'name'=>1,'num'=>1,'site'=>1,'content'=>1
],
1=>[
'type'=>2,'name'=>2,'num'=>2,'site'=>2,'content'=>2
],
2=>[
'type'=>3,'name'=>3,'num'=>3,'site'=>3,'content'=>3
],
3=>[
'type'=>4,'name'=>4,'num'=>4,'site'=>4,'content'=>4
]
)</code>
Copy after login

所以你要拿'name'???不太可能吧??
一:要么你用$query = "SELECT name FROM test LIMIT $startnum,$pagesize";单独查询name;
二:可以用foreach循环

<code>function foreach($array as $a){
    $name[]=$a['name'];
}
</code>
Copy after login

三:array_column($array,'key') 这个函数好像可以提取某一列的~你试试

$res0 试试?

$res2 是二维数组。

看下$res2的结构就晓得啦。。

参考 http://www.ourlove520.com/php5_doc/function.print-r.html
print_r() 将把数组的指针移到最后边。

然后他要尝试移动index的时候,发现并不是 。所以就报一个notice
而且notice并不影响 一般平时我们错误级别都把notice关闭的

用 var_dump(); 调试输出看类型

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!