检查MySQL是否仍处于连接状态或断开连接状态


Check if MySQL is still connected or disconnected

基本上,我在伪代码中尝试做的是:

if button_1_press {
    if connection_doesnt_exist{
        create_connection
        echo "connected"
    }
    else {
        echo "still connected"
    }
}
if button_2_press{
    if connection_exist{
        close_connection
        echo "disconnected"
    }
    else {
        echo "still disconnected"
    }
}

我尝试了一些方法,到目前为止我拥有的最好的是:

.HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <script type='text/javascript' src='script.js'></script>
        <title>PHP AJAX Example</title>
    </head>
    <body>
        <input type='submit' onclick='makeRequest();' value='Connect' id='b1'/>
        <input type='submit' onclick='makeRequest();' value='Disconnect' id='b2'/>
        <div id='ResponseDiv'>
        This is a div to hold the response.
        </div>
</body>
</html>

Javascript:

var xmlHttp = createXMLHttpRequest();
function createXMLHttpRequest(){
    var xmlHttp;
    if (window.ActiveXObject){
        try {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch(e) {
            xmlHttp = false;
        }
    }
    else {
        try {
            xmlHttp = new XMLHttpRequest();
        } 
        catch(e) {
            xmlHttp = false;
        }   
    }
    if(!xmlHttp){
        alert("Error creating the XMLHttpRequest object.");
    }
    else{
        return xmlHttp;
    }
}

function makeRequest(){
    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 4){
            HandleResponse();
        }
    }
    document.getElementById("b1").onclick = function () {xmlHttp.open("GET", "mysql.php?button=1", true); xmlHttp.send(null);}
    document.getElementById("b2").onclick = function () {xmlHttp.open("GET", "mysql.php?button=2", true); xmlHttp.send(null);}
}
function HandleResponse(){
    response = xmlHttp.responseText;    
    document.getElementById('ResponseDiv').innerHTML = response;
}

.PHP

<?php 
$servername = 'localhost';
$username = 'root';
$password = '';
$conn = new mysqli($servername, $username, $password);
if ($_GET['button']==1){
    if ($conn){
        echo "already connected";
        }
    else {
        $conn = new mysqli($servername, $username, $password);
        echo " connected";
    }
}
if ($_GET['button']==2){
    if ($conn){
        echo "disconnected";
        $conn->close();
    }
    else {
        echo "still disconnected";
    }
}
?>

我的问题是:

1)当第一次点击任何按钮时,它什么也不做;仅从第二次单击开始工作。

2)按钮"已连接"始终显示"已连接"。

3)按钮"断开连接"始终显示"已断开连接"

我的理解是发生这种情况,因为每次按下按钮时,makeRequest 函数都会进行 AJAX 调用,每次都会创建一个 mysqli 连接,因此在评估它是否打开的那一刻,它总是正确的,但我不知道如何解决它。

这完全没有意义。

默认情况下,PHP 会在脚本退出时关闭/清理所有打开的连接。因此,每次执行 AJAX 请求来测试数据库连接时,无论如何都会打开一个新的数据库连接,从不测试以前的连接。

您可以使用持久数据库连接,但即使这样,也不能保证您获得与上次相同的连接。你会从开放连接池中获得一些随机连接,这对测试毫无意义。

使用持久连接也会带来大量问题。坚持下去的微观好处与它会导致的所有问题相比相形见绌。