Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

447
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda