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条)

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)