如何检查PHP是否已连接到数据库? [英] How do I check if PHP is connected to a database already?

查看:308
本文介绍了如何检查PHP是否已连接到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上在伪代码中,我正在寻找类似的东西

Basically in pseudo code I'm looking for something like

if (connected_to_any_database()) {
    // do nothing
}
else {
    mysql_connect(...)
}

我该如何实现

connected_to_any_database()

推荐答案

您是否尝试过 mysql_ping() ?

Have you tried 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
}


更新:从PHP 5.5开始,使用 mysqli_ping() .


Update: From PHP 5.5 onwards, use mysqli_ping() instead.

这篇关于如何检查PHP是否已连接到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆