php - 如何使用数据库作为变量进行查询
问题描述
我有两个数据库 -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);
一切正常,直到db
ajax 请求中的变量 - 例如:
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
}
有什么帮助吗?
解决方案
根据$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
}
推荐阅读
- c# - 将未引用的 DLL 合并为一个
- amazon-web-services - Gitlab 共享跑步者 + liquibase
- c++ - 使用 RegSetValueEx 将文件路径添加到注册表中
- rust - 在 Raspberry Pi 中使用 gpio-cdev 和 Rust 将标志重置为正常
- sql - 分区时使用 PostgreSQL 案例
- node.js - 带有房间的 Socket IO 私人消息不起作用
- json - SignalR如何使用打字稿客户端接收64位整数
- ios - .unredacted() SwiftUI - 占位符
- java - 这个(可能是恶意的)Java 代码试图做什么?
- unity3d - 如何统一分割图像