我已经创建了php文件来从数据库(db1)加载数据。在不同的位置和设置(如host,user,pass和db_name)分别有10个以上的数据库。使用相同的PHP代码,我想切换beetwen数据库(使用1个连接文件)。
这是connection.php:
<?php
$db_host = "192.152.8.2";
$db_user = "root";
$db_pass = "toor";
$db_name = "db1";
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if(mysqli_connect_errno()){
echo 'Database Connection Failed : '.mysqli_connect_error();
}
$db_host2 = "192.152.9.5";
$db_user2 = "root";
$db_pass2 = "rooter";
$db_name2 = "db2";
$conn = mysqli_connect($db_host2, $db_user2, $db_pass2, $db_name2);
if(mysqli_connect_errno()){
echo 'Database Connection Failed : '.mysqli_connect_error();
}
?>
这是控制器:
<?php
$db = @new MySQLi ("$db_host","$db_user","$db_pass","$db_name");
$db->connect_errno and die('Koneksi database gagal: '.$db->connect_error);
//Query the data
$res = $db->query("SELECT COUNT(*) from student where ipSemId='".$ipSemId."'")
or die($db->error);
?>
现在,我手动创建(通过更改$ db变量)。还有其他方法可以简化(也许使用if..else)?请提出建议。谢谢。