Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

445
Views
PHP MongoDB exception (Error handling)

I have a PHP platform where user write mongodb query like picture below

enter image description here

and following code print result as a table

$m = new MongoClient();
$db = $m->Forensic;
$coll= $db->mobile_data;

if (isset($_POST['txt_area']) && !empty($_POST['txt_area'])) { 


    $d = ($_POST['txt_area']);
    $p = json_decode($d);
    $user_code = $coll->find($p);

When I type correct code system able to ouput all my result but if I write query wrong I am getting error message like

Warning: MongoCollection::find(): expects parameter 1 to be an array or object, null given in C:\xampp\htdocs\reports5.php on line 126

to catch that error i have tried following try catch code but no luck

 try {
if (isset($_POST['txt_area']) && !empty($_POST['txt_area'])) { 


    $d = ($_POST['txt_area']);
    $p = json_decode($d);
    $user_code = $coll->find($p);

    $NumberOfRow2 = $user_code->count();

    $user_code->sort(array('Chat_group' => -1, 'Instant_Message' => 1 ));

}
}

catch (MongoCursorException $e) {
    echo "error message: ".$e->getMessage()."\n";
    echo "error code: ".$e->getCode()."\n";
}

catch (MongoException $e) 
{
    echo $e->getMessage();
}
catch(MongoResultException $e) {
    echo $e->getMessage(), "\n";
    $res = $e->getDocument();
    var_dump($res);
}

what would be the best way to catch above error

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The warning you're seeing is PHP complaining that $coll->find($p); expects $p to be either array or object while it's null. Quoting json_decode documentation:

NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

So a proper way to defend against warning would be:

$p = json_decode($d);
if ($p === null) {
    echo "Provided query is invalid!";
} else {
    // do your logic
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!