doupao6011 2011-05-08 00:10
浏览 33
已采纳

推/弹当前数据库

I have a simple PHP / MySql application which will generally pick one of several databases (let's say one per customer) to manipulate. However, there are frequent calls to utility functions which access a common database.

I don't want to sprinkle USE clauses throughout my code, so it looks like I ought to push the current database at the start of each utility function and pop it again at the end. Something like this (from the top of my head, so prolly won't work, but will give an idea).

function ConnectToDatabase($db)
{
   global $current_database;
   $current_database = $db;
   odb_exec('USE ' . $db);  // etc. Error handling omitted for clarity
}

function UtilityFunction()
{
   odb_exec('USE common_db');  // etc. Error handling omitted for clarity
   // do some work here
   global $current_database;
   ConnectToDatabase($current_database);
}

Maybe I can make it prettier by combining global $current_database; ConnectToDatabase($current_database); into a PopCurrentDb function, but you get the picture.

is this better done in PHP? Is there a MySql solution (but later I want to be ODBC compliant, so maybe PHP is better). How do others do it?


Update: in the end I just decided to always fully qualify access,
e.g. SELECT * from $database . '.' . $table

  • 写回答

2条回答 默认 最新

  • dongmei3869 2011-05-08 01:57
    关注

    Why dont you just make some kind of database manager class and just push that around? Centralize all you dbname/connection storage in a single entity. that way you have a clear api to access it and you can just use the db by name.

    class MultiDb
    {
    
       /*
        * Array of PDO DB objects or PDO DSN strings indexed by a connection/dbname name
        *
        * @var array
        */
       protected $connections = array();
    
       /*
        * The connection name currently in use
        * @var string
        */
       protected $currentConnection;
    
       /*
        * The Defualt connection name
        *
        * @var string
        */ 
       protected $defaultConncetion;
    
       /*
        * @param array $connections Any array DSN or PDO objects
        */ 
       public function __construct(array $connections);
    
       public function getConnection($name);
    
       // i would set this up to intelligently return registered connections
       // if the argument matches one
       public function __get($name)
    
       // same with __set as with __get
       public function __set($name, $value);
    
       // proxy to the current connection automagically
       // if current isnt set yet then use default so things
       // running through this would actually result in
       // call_user_func_array(array(PDO $object, $method), $args);
    
       public function __call($method, $args);
    
    }
    

    So usage might look like

    // at the beginning of the app
    
    $db = new MultiDb(array(
       'util' => array('mysql:host=localhost;dbname=util;', 'user', 'pass');
       'default' => array('odbc:DSN=MYDSN;UID=user;PWD=pass;');
    ));
    
    
    // some where else in the app we want to get some ids of some entities and then
    //  we want to delete the associated logs in our shared utility DB
    
    // fetch the ids from the default db
    
    $ids = $db->default->query('SELECT c.name, c.id FROM some_table c')
      ->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // assume we have written a method 
    // to help us create WHERE IN clauses and other things
    $in = $db->createQueryPart($ids, MultiDb::Q_WHERE_IN); 
    
    // prepare our delete from the utility DB
    $stmt = $db->util->prepare(
      'DELETE FROM log_table WHERE id IN('.$in['placeholder'].')', 
      $in['params']
    );
    
    // execute our deletion
    $stmt->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。