php 如何检查我是否已连接到数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12225318/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:04:35  来源:igfitidea点击:

How do I check if I'm connected to database?

phpmysqlconnectionconditional-statements

提问by lisovaccaro

This is the code to connect to the mysql database:

这是连接mysql数据库的代码:

$con = mysql_connect("", "", "");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("", $con);

I want to echo 'connected'/'disconnected' depending on state.

我想根据状态回显“已连接”/“已断开连接”。

How can it be done?

怎么做到呢?

回答by Danil Speransky

Do it Like this

像这样做

if ($con) {
  echo 'connected';
} else {
  echo 'not connected';
}

Or try this

或者试试这个

echo $con ? 'connected' : 'not connected';

回答by Spudley

Firstly, use the mysqli_xxx()functions instead of the old obsolete mysql_xx()functions.

首先,使用mysqli_xxx()函数代替旧的过时mysql_xx()函数。

This is strongly recommended anyway because the old library is in the process of being deprecated, but will also make your question easier to answer. (you could also use the PDO library, for which the answer will be similar, but for this answer I'll stick with mysqli for simplicity)

无论如何强烈建议这样做,因为旧库正在被弃用,但也会使您的问题更容易回答。(您也可以使用 PDO 库,其答案是相似的,但对于这个答案,为了简单起见,我将坚持使用 mysqli)

With the mysqlilibrary, you get a variable that contains your DB connection, which you can examine at any point.

使用该mysqli库,您将获得一个包含数据库连接的变量,您可以随时检查该变量。

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

Now, you can query the $mysqlivariable to find out what is happening.

现在,您可以查询$mysqli变量以了解发生了什么。

if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

Later on, you can query the variable using the pingcommand: http://www.php.net/manual/en/mysqli.ping.php

稍后,您可以使用以下ping命令查询变量:http: //www.php.net/manual/en/mysqli.ping.php

$mysqli->ping();

or maybe the statcommand if you want more info: http://www.php.net/manual/en/mysqli.stat.php

或者stat如果你想了解更多信息,可以使用命令:http: //www.php.net/manual/en/mysqli.stat.php

回答by Sibu

Try using mysql_ping

尝试使用mysql_ping

mysql_ping — Ping a server connection or reconnect if there is no connection

mysql_ping — 如果没有连接,则 Ping 一个服务器连接或重新连接

something like this should help you

这样的事情应该可以帮助你

if(mysql_ping($con)) 
  echo 'connected'; 
 else 
  echo 'disconnected';