duanfu6160 2019-08-19 07:25
浏览 118
已采纳

PHP Mongodb中的动态数据库选择

Not able to select the database and collection dynamically. Read all the solutions but not working for me. selectDB function not working. It's working only with the static data.

I want to select the database from the configuration file and also select the collections dynamically.

$username='abcd';
$password='efgh';
$m = new MongoDB\Client("mongodb://abcd@127.0.0.1:28015/ijkl", array("username" => $username, "password" => $password));

$db = $m->ijkl;

but I want to have it like

$username='abcd';
$password='efgh';
$m = new MongoDB\Client("mongodb://abcd@127.0.0.1:28015/ijkl", array("username" => $username, "password" => $password));

$l1="ijkl";
$db = $m->$l1;

Expecting to work with dynamic database selection.

  • 写回答

2条回答 默认 最新

  • dtkf64283 2019-08-19 09:55
    关注

    Finally it's working

    $m = new MongoDB\Client("mongodb://".$mongo_username."@".$mongo_ip.":".$mongo_port."/".$mongo_db, array("username" => $mongo_username, "password" => $mongo_password));
    
    
     if(!empty($db = $m->$mongo_db))
     {
         $collection = "test";
    
       if(!empty($collection = $db->$collection))
       {
    
        $cursor =$collection->find(array("status"=>0), ['limit' => 10,'skip'=>10]);
    
         foreach ($cursor as $document) {
    
            echo "<b>ID is:</b>";
            echo $id=$document["_id"];
            echo "<br>";
            echo "<b>Link is:</b>";
            echo $link=$document["Link"];
            echo "<br>";
            echo "<b>Status is:</b>";
            echo $status=$document["status"];
            echo "<br>";
            echo "<b>Label is:</b>";
            echo $label=$document["Label"];
            echo "<br>";
    
    
        }
       }
       else
       {
           echo "Not able to select the collection!";
       }
     }
     else
     {
         echo "Not able to select the database!";
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分