当前位置:Gxlcms > PHP教程 > 为什么print_r()能查询出数据来为什么加上键名就查不出来了?

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

时间:2021-07-01 10:21:17 帮助过:4人阅读

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

这是数据库的内容

  1. <code><!--?php
  2. header('content-type:text/html;charset=utf-8;');
  3. $pdo=new PDO("mysql:host=localhost;dbname=t1","root","");
  4. $stmt=$pdo--->prepare("select * from test");
  5. $stmt->execute();
  6. $res=$stmt->fetchall();
  7. $rows=count($res);
  8. $pagesize=3;
  9. $pagenum=ceil($rows/$pagesize);
  10. $page=empty($_GET['page'])?1:$_GET['page'];
  11. $startnum = ($page - 1)*$pagesize;
  12. $query = "SELECT * FROM test LIMIT $startnum,$pagesize";
  13. $stmt2=$pdo->prepare($query);
  14. $stmt2->execute();
  15. $res2=$stmt2->fetchall();
  16. print_r($res2['name']);
  17. ?></code>

回复内容:

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

这是数据库的内容

  1. <code><!--?php
  2. header('content-type:text/html;charset=utf-8;');
  3. $pdo=new PDO("mysql:host=localhost;dbname=t1","root","");
  4. $stmt=$pdo--->prepare("select * from test");
  5. $stmt->execute();
  6. $res=$stmt->fetchall();
  7. $rows=count($res);
  8. $pagesize=3;
  9. $pagenum=ceil($rows/$pagesize);
  10. $page=empty($_GET['page'])?1:$_GET['page'];
  11. $startnum = ($page - 1)*$pagesize;
  12. $query = "SELECT * FROM test LIMIT $startnum,$pagesize";
  13. $stmt2=$pdo->prepare($query);
  14. $stmt2->execute();
  15. $res2=$stmt2->fetchall();
  16. print_r($res2['name']);
  17. ?></code>

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

  1. <code>array(
  2. 0=>[
  3. 'type'=>1,'name'=>1,'num'=>1,'site'=>1,'content'=>1
  4. ],
  5. 1=>[
  6. 'type'=>2,'name'=>2,'num'=>2,'site'=>2,'content'=>2
  7. ],
  8. 2=>[
  9. 'type'=>3,'name'=>3,'num'=>3,'site'=>3,'content'=>3
  10. ],
  11. 3=>[
  12. 'type'=>4,'name'=>4,'num'=>4,'site'=>4,'content'=>4
  13. ]
  14. )</code>

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

  1. <code>function foreach($array as $a){
  2. $name[]=$a['name'];
  3. }
  4. </code>

三: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(); 调试输出看类型

人气教程排行