Verify Connection Existence with MySQL in PHP

4

I came across this question recently, how to check if there is an open connection to mysql? Everyone knows that in order to use mysql_real_escape_string need to have a certain connection, so I wanted to check if there is one, if yes then use mysql_real_escape_string .

    
asked by anonymous 10.04.2014 / 15:49

3 answers

7

You can check this:

<?php
if(is_resource($connection) && get_resource_type($connection) === 'mysql link')
{
    //esta conectado.
}
else
{
    //não está conectado
}
?>

or simply this one that returns false if there is no connection:

mysql_thread_id($connection)

Source: SO.com

    
10.04.2014 / 16:03
6

The mysql_ping function returns FALSE if there is no connection, with the advantage of trying to reconnect before, if the connection has been lost in a script:

mysql_ping ([ $identificador_da_conexao ] )

See the manual:

link

  

Important: mysql_ functions do not exist since PHP 5.5. Learn how to use mysqli_ functions, which are more secure and complete. Click here and see the documentation .

    
10.04.2014 / 16:58
2

Thank you Jorge B.! The solution that works best is:

<?php


if(is_resource($connection) && get_resource_type($connection) === 'mysql link'){

//esta conectado.

} else {

//não está conectado

}


?>

Because using mysql_ping() or mysql_thread_id() , when the connection is terminated, these commands return error, since there is no resource for them to work ...

    
13.06.2015 / 12:41