如何检查 PHP 是否已连接到数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5148033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check if PHP is connected to a database already?
提问by deltanovember
Basically in pseudo code I'm looking for something like
基本上在伪代码中,我正在寻找类似的东西
if (connected_to_any_database()) {
// do nothing
}
else {
mysql_connect(...)
}
How do I implement
我如何实施
connected_to_any_database()
回答by mailo
Have you tried mysql_ping()?
你试过mysql_ping()吗?
Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted.
检查与服务器的连接是否正常。如果它已关闭,则会尝试自动重新连接。
Alternatively, a second (less reliable) approach would be:
或者,第二种(不太可靠的)方法是:
$link = mysql_connect('localhost','username','password');
//(...)
if($link == false){
//try to reconnect
}
Update:From PHP 5.5 onwards, use mysqli_ping()instead.
更新:从 PHP 5.5 开始,使用mysqli_ping()代替。
回答by McHerbie
Try using PHP's mysql_pingfunction:
尝试使用 PHP 的mysql_ping函数:
echo @mysql_ping() ? 'true' : 'false';
You will need to prepend the "@" to suppose the MySQL Warnings you'll get for running this function without being connected to a database.
您需要在“@”前面加上“@”,以假设您在未连接到数据库的情况下运行此函数会得到 MySQL 警告。
There are other ways as well, but it depends on the code that you're using.
还有其他方法,但这取决于您使用的代码。
回答by azat
回答by Capsule
before... (I mean somewhere in some other file you're not sure you've included)
之前...(我的意思是在其他文件中的某个地方,您不确定是否已包含在内)
$db = mysql_connect()
later...
之后...
if (is_resource($db)) {
// connected
} else {
$db = mysql_connect();
}
回答by ergohack
Baron Schwartz blogs that due to race conditions, this 'check before write' is a bad practice. He advocates a try/catch pattern with a reconnect
in the catch. Here is the pseudo code he recommends:
Baron Schwartz 在博客中表示,由于竞争条件,这种“写前检查”是一种不好的做法。他提倡在 catch 中使用一个 try/catch 模式reconnect
。这是他推荐的伪代码:
function query_database(connection, sql, retries=1)
while true
try
result=connection.execute(sql)
return result
catch InactiveConnectionException e
if retries > 0 then
retries = retries - 1
connection.reconnect()
else
throw e
end
end
end
end
Here is his full blog: https://www.percona.com/blog/2010/05/05/checking-for-a-live-database-connection-considered-harmful/
这是他的完整博客:https: //www.percona.com/blog/2010/05/05/checking-for-a-live-database-connection-thinked-harmful/
回答by Pekka
// Earlier in your code
mysql_connect();
set_a_flag_that_db_is_connected();
// Later....
if (flag_is_set())
mysql_connect(....);