1

MongoDB displays an error when it finds a blank entry

 2 years ago
source link: https://www.codesd.com/item/mongodb-displays-an-error-when-it-finds-a-blank-entry.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

MongoDB displays an error when it finds a blank entry

advertisements

I have a project where it searches for a specific entry in a specific column and then returns all documents that have that entry in that column. It works almost perfectly except when that entry field is empty it gives an error. Let me try to illustrate below.

My DB:

A|B|C|D
1|1|5|5
2|1| |6
3|2|7|7
4|2|8|8

My PHP:

$query = array( "B" => 1);
$cursor = $collection->find( $query );

foreach ($cursor as $obj) {
    echo $obj["A"] . $obj["B"] . $obj["C"]  .$obj["D"] . "<br />";
}

My output is:

1155
21Notice: Undefined index: C6

How do I go about not giving any errors. Just treat it as an empty field. I'm not sure if this is a common problem but, I'm still new to PHP and very new to MongoDB.


Use isset() to find out if the key exists in the array before trying to index using it

foreach ($cursor as $obj) {
    echo $obj["A"] . $obj["B"]. (isset($obj["C"]) ? $obj["C"] : '' ) .$obj["D"]."<br />";
   //It will replace each blank with an ''
    }


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK