我正在一个项目中,我需要测试远程MySQL连接,如果失败,那么我需要代码才能切换到使用本地MySQL连接。我遇到的问题是代码始终显示错误,这确实杀死了最终用户体验。
我尝试过的事情:
码:
//-----Remote MySQL Server-----------
$rem_host="99.99.999.999"; //Host Name
$rem_user="testUser"; //MySQL Username
$rem_pass="testPass"; //MySQL Password
$rem_db="testDb"; //Database Name
//----Local MySQL Server-----------
$local_host="127.0.0.1"; //Host Name
$local_user="testLocal"; //MySQL Username
$local_pass="passLocal"; //MySQL Password
$local_db="localDb"; //Database Name
$remoteConnection = mysqli_connect("$rem_host","$rem_user","$rem_pass","$rem_db");
if(!$remoteConnection){ $check_connection=0; }
else{ $check_connection=1; mysqli_close($remoteConnection); }
if($check_connection==1){
$db_host = $rem_host; //Host Name
$db_user = $rem_user; //MySQL Username
$db_pass = $rem_pass; //MySQL Password
$db_name = $rem_db; //Database Name
}
else{
$db_host = $local_host; //Host Name
$db_user = $local_user; //MySQL Username
$db_pass = $local_pass; //MySQL Password
$db_name = $local_db; //Database Name
}
?>
最佳答案
根据您的选择更改第2行。首先,我获取URL,然后检查它是否具有“localhost”一词,然后按照localhost详细信息(我在本地计算机上使用localhost/)。如果$ actual_link无法获取本地主机,请关注在线详细信息
<?php
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (strpos($actual_link,'localhost') !== false)
{
//local db detail
$servername='localhost';
$dbusername='root';
$dbpassword='';
$dbname='db_gbook';
echo "local";
}
else
{
//online db detail
$servername='localhost';
$dbusername='dbaname';
$dbpassword='dbpassword';
$dbname='yourdbname';
echo "web";
}
global $link;
$link=mysql_connect ("$servername","$dbusername","$dbpassword");
if(!$link)
{
die("Could not connect to MySQL");
}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
echo "Succesive";
?>