[英]How do I check if PHP is connected to a database already?
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()
Have you tried mysql_ping() ?你试过mysql_ping()吗?
Update: From PHP 5.5 onwards, use mysqli_ping() instead.更新:从 PHP 5.5 开始,使用mysqli_ping()代替。
Pings a server connection, or tries to reconnect if the connection has gone down. Ping 一个服务器连接,或者在连接断开时尝试重新连接。
if ($mysqli->ping()) { printf ("Our connection is ok!\\n"); } else { printf ("Error: %s\\n", $mysqli->error); }
Alternatively, a second (less reliable) approach would be:或者,第二种(不太可靠的)方法是:
$link = mysql_connect('localhost','username','password');
//(...)
if($link == false){
//try to reconnect
}
Try using PHP's mysql_ping function:尝试使用 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.还有其他方法,但这取决于您使用的代码。
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();
}
Baron Schwartz blogs that due to race conditions, this 'check before write' is a bad practice. Baron Schwartz 在博客中表示,由于竞争条件,这种“写前检查”是一种不好的做法。 He advocates a try/catch pattern with a reconnect
in the catch.他提倡在捕获中reconnect
的 try/catch 模式。 Here is the pseudo code he recommends:这是他推荐的伪代码:
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/
// Earlier in your code
mysql_connect();
set_a_flag_that_db_is_connected();
// Later....
if (flag_is_set())
mysql_connect(....);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.