2

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

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.