dtdfj08626 2016-02-06 12:17 采纳率: 0%
浏览 375

如何从php中获取mongodb集合中的所有记录

I tried the following code for selecting all the records from mongodb collection.But only last inserted record will come.

<?php 
$m=new MongoClient();
$db=$m->trip;
if($_SERVER['REQUEST_METHOD']=="POST")
{
    $userId=$_POST['userId'];
    $param=explode(",",$userId);
    $collection=$db->chat;
    $record=$collection->find(array("userId"=>$userId));
    if($record)
    {
        foreach($record as $rec)
        {
            $json=array("msg"=>$rec);
        }
    }
    else
    {
        $json=array("msg"=>"No Records");
    }
}
else
{
    $json=array("msg"=>"Request Method is Not Accespted");
}
//output header
header('Content-type:application/json');
echo json_encode($json);

?>

But only one record will come please help me

  • 写回答

1条回答 默认 最新

  • douqilai4263 2016-02-06 12:34
    关注

    Your problem is that each time your foreach executes, it overrides the content of $json variable. Try declaring $json first and then using it.

    if($record)
    {
        $json = array();
        foreach($record as $rec)
        {
            $json[] = array("msg"=>$rec);
            //   /\ this means adding the attribution to the end of the array.
        }
    }
    

    This way, each time the foreach is executed, the content of $json won't be replaced, instead it will be appended.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集