推/弹当前数据库

时间:2011-05-08 00:10:21

标签: php mysql

我有一个简单的PHP / MySql应用程序,通常会选择几个数据库中的一个(假设每个客户一个)进行操作。但是,经常调用访问公共数据库的实用程序函数。

我不想在我的代码中添加USE子句,所以看起来我应该在每个实用程序函数的开头推送当前数据库并在结束时再次弹出它。像这样的东西(从我的头顶,如此繁重将无法工作,但会给出一个想法)。

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);
}

也许我可以通过将global $current_database; ConnectToDatabase($current_database);合并到PopCurrentDb函数中来让它变得更漂亮,但是你可以了解它。

这在PHP中做得更好吗?是否有MySql解决方案(但后来我想要符合ODBC,所以也许PHP更好)。其他人如何做到这一点?


更新:最后我决定始终完全符合访问权限,
例如SELECT * from $database . '.' . $table

2 个答案:

答案 0 :(得分:4)

为什么你不只是制作某种数据库管理器类而只是推动它?将所有dbname / connection存储集中在一个实体中。这样你就可以有一个明确的api来访问它,你可以按名称使用db。

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

}

所以用法看起来像

// 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 :(得分:1)

所以你想要创建一个推(插入)和弹出(选择和删除)的功能? 您可以创建一个存储过程来处理这个问题,或者您可以在php中编写多个查询执行。