How to fetch all the records from mongodb collection in php -
i tried following code selecting records mongodb collection.but last inserted record 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 $rec) { $json=array("msg"=>$rec); } } else { $json=array("msg"=>"no records"); } } else { $json=array("msg"=>"request method not accespted"); } //output header header('content-type:application/json'); echo json_encode($json);
?>
but 1 record come please me
your problem each time foreach
executes, overrides content of $json
variable. try declaring $json
first , using it.
if($record) { $json = array(); foreach($record $rec) { $json[] = array("msg"=>$rec); // /\ means adding attribution end of array. } }
this way, each time foreach
executed, content of $json
won't replaced, instead appended.
Comments
Post a Comment