Skip to content
Advertisement

Specify Mongo DB and Collection name as variables in PHP

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

JavaScript

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

JavaScript

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?

JavaScript

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

JavaScript

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement