dongmuzhan4705 2009-10-05 12:45
浏览 56
已采纳

PDO循环并打印fetchAll

I'm having trouble getting my data from fetchAll to print selectively.

In normal mysql I do it this way:

$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)){
   $id = $row['id'];
   $n = $row['n'];
   $k = $row['k'];
}

In PDO, I'm having trouble. I bound the params, then I'm saving the fetched data into $rs like above, with the purpose of looping through it the same way..

$sth->execute();
$rs = $query->fetchAll();

Now comes the trouble part. What do I do PDO-wise to get something matching the while loop above?! I know I can use print_r() or dump_var, but that's not what I want. I need to do what I used to be able to do with regular mysql, like grabbing $id, $n, $k individually as needed. Is it possible?

Thanks in advance..

  • 写回答

1条回答 默认 最新

  • doubu1970 2009-10-05 12:53
    关注

    It should be

    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
      $id = $row['id'];
      $n = $row['n'];
      $k = $row['k'];
    }
    

    If you insist on fetchAll, then

    $results = $query->fetchAll(PDO::FETCH_ASSOC);
    foreach($results as $row) {
       $id = $row['id'];
       $n = $row['n'];
       $k = $row['k'];
    }
    

    PDO::FETCH_ASSOC fetches only column names and omits the numeric index.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度