• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 3年前 (2022-01-25) 19次浏览 已收录 0个评论
文章目录[隐藏]

<body>

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

这是数据库的内容

<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>

回复内容:

<body>

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

这是数据库的内容

<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>

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

<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>

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

<strong>+本文来源gao@daima#com搞(%代@#码网</strong><pre>搞代gaodaima码

function foreach($array as $a){ $name[]=$a['name'];}

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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:为什么print_r()能查询出数据来为什么加上键名就查不出来了?

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址