首页 > 解决方案 > 如何使用php在mongodb中动态给出数据库名称

问题描述

<?php
require '../mongodb/vendor/autoload.php';
use MongoDB\Client as Mongo;
//connect to mongodb
$user = "admin";
$pwd = '********';
$mongo = new Mongo("mongodb://${user}:${pwd}@127.0.0.1:27017");
//connecting to mongodb end

$collection=NULL;
$projectid = (int)$_POST["projectid"];
if($projectid == 1)
$collection = $mongo->saveddesignes->kitchen_SavedDesignes; // want assing db and collection name dynamically in this line
//add other projects in if condition


$userid = (int)$_POST["storeid"];
$companyid = (int)$_POST["companyid"];
if($collection!=null){
$cursor = $collection->find(["StoreID"=>$userid,"StoreID"=>$companyid]);
foreach ($cursor as $document) {
echo json_encode($document)."&eod&";
 }
 }

?>

上面的代码工作正常。但我希望数据库名称和集合名称是动态的,我该如何实现。

谢谢

标签: phpmongodbphplib

解决方案


推荐阅读