3

MongoDB's PHP library allows me to connect to a collection like this (from example):

$m = new Mongo(); 
$db = $m->comedy; 
$collection = $db->cartoons;

But how do I specify the database and/or the collection name as a variable? What I want to do is something like this:

$m = new Mongo();
$dbname = "comedy"; 
$collectionname = "cartoons"; 
$db = $m[$dbname]; 
$collection = $db[$collectionname];

I can do this using the Python API, so I find it strange that I am not able to do it using PHP.

UPDATE: This is the error I am getting when I use the above method, which leads me to believe there's no built-in way to address MongoDB collections using variable names?

Fatal error: Cannot use object of type Mongo as array

ANSWER: As per accepted answer below, this will work:

$db = $m->$dbname; 
$collection = $db->$collectionname;

3 Answers 3

3

You can still get it by a variable using -> ie $m->$dbname via http://php.net/manual/en/mongo.tutorial.php

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, just edited it. But that didn't fix it - this is the error I get: "Fatal error: Cannot use object of type Mongo as array"
You can still get it by a variable using -> ie $m->$dbname via php.net/manual/en/mongo.tutorial.php
Ah, that did work! Thanks, can you edit/update your answer? Marking this as right?
0

Updated code for mongodb library:

$dbname = "comedy";
$collectionname = "cartoons";
$collection = (new MongoDB\Client("mongodb://".$config["MONGO_USER"].":".$config["MONGO_PASS"]."@".$config["MONGO_SERVER"]."/".$dbname))
        ->{$dbname}->{$collectionname};

$insertOneResult = $collection->insertOne([
    'data'=>"my data"
]);

Comments

-1

That will work with the provision that the "names" used are valid var names in PHP (ex. if you use a space on the "collection" name, it will fail).

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.