简体   繁体   English

如何强制重新连接到 php 中的数据库?

[英]How do I force reconnecting to my database in php?

I wanted my web system to automatically reconnect to the database if it reaches to maximum user connection.我希望我的 web 系统在达到最大用户连接时自动重新连接到数据库。 Or is there anyway i could reload the page automatically till it is connected to the database或者无论如何我可以自动重新加载页面,直到它连接到数据库

$conn =  new mysqli(DB_HOST,DB_USER,DB_PSWD,DB_NAME);

if($conn->connect_error)
die("Failed to connect database ".$conn->connect_error );

You can setting the retry variable( $retry ) as a flag to mark the DB connection status with default value you want.您可以将重试变量( $retry )设置为标志,以使用您想要的默认值标记数据库连接状态。 While connect DB, if it's ok then update retry flag = 0( $retry=0 ), else reduce the retry one unit ( $retry-- ).连接数据库时,如果可以,则更新重试标志 = 0( $retry=0 ),否则减少重试单位 ( $retry-- )。 Also you don't die process when have error exception.此外,当出现错误异常时,您不会die进程。

You can enclose the connection in a function and call it many times you want to retry the connection:您可以将连接包含在 function 中,并多次调用它来重试连接:

function connectDB(DB_HOST,DB_USER,DB_PSWD,DB_NAME)
{
    return $conn = new mysqli(DB_HOST,DB_USER,DB_PSWD,DB_NAME);
}


if(connectDB()->connect_error)
{
    sleep(1);
    if(connectDB()->connect_error)
    {
        die("Failed to connect database ".$conn->connect_error );
    }
}

With sleep(1) you delay the script to retry the connection after 1 second.使用sleep(1)您可以延迟脚本在 1 秒后重试连接。

Anyway, you should find the cause of the connection error and solve it;无论如何,您应该找到连接错误的原因并解决它; this solution may help you in the case the server is sometimes slow to respond.如果服务器有时响应缓慢,此解决方案可能会对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM