Check if MySQL is still connected or disconnected
11:24 11 Jun 2015

Basically, what i'm trying to do in pseudo-code is this:

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"
    }
}

I tryed some approaches, the best i have so far is this:

HTML



    
        
        PHP AJAX Example
    
    
        
        
        
This is a div to hold the response.

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

close();
    }
    else {
        echo "still disconnected";
    }
}

?>

My problems are:

1) When any of the buttons is clicked for the first time, it does nothing; only starts working from the second click.

2) Button "Connected" always shows "already connected".

3) Button "Disconnect" always shows "disconnected"

What I understand is this happen because every time a button is pressed, the makeRequest function makes an AJAX call, which creates a mysqli connection every time, so at the moment of evaluate if its open, it always will be true, but I have no idea how to fix it.

php mysqli