How do I check if PHP is connected to a database already?

前端 未结 6 2344
误落风尘
误落风尘 2020-12-09 14:29

Basically in pseudo code I\'m looking for something like

if (connected_to_any_database()) {
    // do nothing
}
else {
    mysql_connect(...)
}
6条回答
  •  無奈伤痛
    2020-12-09 15:28

    Try using PHP's mysql_ping function:

    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.

    There are other ways as well, but it depends on the code that you're using.

提交回复
热议问题