【发布时间】:2019-01-29 04:18:16
【问题描述】:
我有 2 个不同的服务器数据库,然后我想创建一个连接函数,以便我可以使用连接表从不同的数据库中检索数据。 之前我做了如下功能,只有那些连接到本地数据库的...
<?php
//Constants to connect with the database local
define('DB_USERNAME_LOCAL', 'root');
define('DB_PASSWORD_LOCAL', '');
define('DB_HOST_LOCAL', 'localhost');
define('DB_NAME_LOCAL', 'db_attendance');
//Constants to connect with the database server
define('DB_USERNAME_SERVER', '******');
define('DB_PASSWORD_SERVER', '******');
define('DB_HOST_SERVER', '*********');
define('DB_NAME_SERVER', 'rlempl');
class DbConnect
{
//Variable to store database link
private $con;
//This method will connect to the database
function connect()
{
//connecting to mysql database
$this->con = new mysqli(DB_HOST_LOCAL, DB_USERNAME_LOCAL, DB_PASSWORD_LOCAL, DB_NAME_LOCAL);
$this->con = new mysqli(DB_HOST_SERVER, DB_USERNAME_SERVER, DB_PASSWORD_SERVER, DB_NAME_SERVER);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//finally returning the connection link
return $this->con;
}
}
// this is function for query
<?php
class DbOperation
{
private $con;
function __construct()
{
require_once dirname(__FILE__) . '/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
// this query join 2 table with diferent database
public function dataExist($pin, $date){
$stmt = $this->con->prepare("SELECT b.rldate FROM tams_fingerid a JOIN tams_attlog b ON b.rlcode=a.rlcode WHERE a.fingerid='$pin' AND b.rldate='$date'");
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
$stmt->close();
return $num_rows > 0;
}
【问题讨论】:
-
$this->confor local 每次都会被覆盖。它将如何决定连接哪个数据库。传递一些标识符来决定connect()。 -
那么,我该怎么办?用变量替换它?