如果localhost连接失败或无法访问,我尝试编写连接到在线服务器的脚本。我有下面的脚本连接到localhost数据库,如果它不可访问,则重新路由到服务器连接。脚本不知何故无法工作,我只是不知道为什么。有人有什么建议吗?
<?php
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'admin';
$DB_CON_A = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);
if(!$DB_CON_A) {
die($DB_CON_A);
$DB_HOST = 'www.xyz.com';
$DB_USER = 'admin';
$DB_PASS = '1235kasK';
$DB_NAME = 'admin';
}
try {
$DB_CON_A = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
$DB_CON_A->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
答案 0 :(得分:0)
以下是我为那些正在寻找的人提供的解决方案:
<?php
function ping($DB_HOST) {
exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($DB_HOST)), $res, $rval);
return $rval === 0;
}
$DB_HOST = 'www.xyz.com';
$connected = ping($DB_HOST);
if ($connected) {
$DB_HOST = 'www.xyz.com';
$DB_USER = 'user';
$DB_PASS = 'pass';
$DB_NAME = 'accounts';
} else {
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'accounts';
}
// Create database if not exists
$DB_CON_C = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);
$DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DB_CON_C->query("CREATE DATABASE IF NOT EXISTS $DB_NAME");
$DB_CON_C->query("USE $DB_NAME");
try {
$DB_CON_C = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
$DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
?>