简体   繁体   中英

How to fetch all the records from mongodb collection in php

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM