dpca31461 2013-12-18 23:43
浏览 72
已采纳

如何在单个会话期间更改数据库

I need to achieve the functionality where users can change databases on the fly. Once changed, the current database will be used across all php files making db calls.

So, I am trying to find the best solution to switch and remember the current database params during a single session. This is what I am doing at the moment:

1) php connection files conn1.php, conn2.php, conn3.php etc. containing different database connection parameters (name, password etc - $hostname, $username and so on).

2) when a user changes the database, the current database code is saved as a session variable $currDB.

3) All files that contains db calls, have a db connection switch on the top:

switch ($currDB){
     case 1:
          require_once('conn1.php');
          break;
     case 2:
          require_once('conn2.php');
          break;
    ........
}
$mysqli = new mysqli($hostname,$username,$password,$database);

Is there a more elegant way of achieving the same functionality of switching databases based on the user selection? I am not sure if maintaining session vars across multiple files would be the best option.

Any better ideas?

Thanks

  • 写回答

2条回答 默认 最新

  • dongzhou8764 2013-12-18 23:49
    关注

    I recommend, you do something like

    • get $currentDB from the session or user input
    • sanitize it to an int, either via (int) or e.g. is_numeric() followed by abs(round(..)) on very old PHP versions

    now just @require_once("conn$currentDB.php"); and check for errors.

    Last step is to put this into conn.php and include it from all consumers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?