首页 > 解决方案 > 如何使用数据库作为变量进行查询

问题描述

我有两个数据库 -lorem并且nts.lorem- 需要同时使用它们

$user = 'root';
$pass = '';
$db1 = new PDO('mysql:host=localhost; dbname=nts.lorem', $user, $pass);
$db2 = new PDO('mysql:host=localhost; dbname=lorem', $user, $pass);

一切正常,直到dbajax 请求中的变量 - 例如:

js

var db;
if(something is true){db = 'db1';};
else{db = 'db2';}
//... ajax post code

php

function something($db){
    global $db1, $db2;
    // how to say the next line  
    $sq = "select id from " . $db . ".tableName order by title asc";
    // error - table db1.tableName doesn't exist  
}

有什么帮助吗?

标签: phpmysql

解决方案


根据$db值选择连接:

function something($db){
    global $db1, $db2;
    $sq = "select id from tableName order by title asc";
    if ($db === 'db1') {
        $db1->execute($sq);
    } else {
        $db2->execute($sq);
    }    
    // rest of the code  
}

推荐阅读