Check Mysql Connection Existence in PHP

Asked

Viewed 2,818 times

5

I had this question recently, how to check if there is an open connection with mysql? Everyone knows that to use the mysql_real_escape_string need to have a connection right, so I wanted to check if there is one, if yes ai use mysql_real_escape_string.

  • 2

    A little strange question, because, by your code you can know if you have connection or not, a thing also and a tip stop using mysql_connect, this code is deprecated in the new versions of your PHP, so use PDO (http://us1.php.net/manual/en/class.pdo.php) or Mysqli (http://us1.php.net/manual/en/class.mysqli.php) At this link you can get the error simply by mysql_error (http://us1.php.net/manual/en/function.mysql-error.php), the first example can help you !!!

  • 2

3 answers

7

You can check like 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 AS.

7

The function mysql_ping 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:

http://br1.php.net/manual/en/function.mysql-ping.php

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

  • 2

    Here comes the question: First of all, you are opening the connection in your code?

  • 3

    And there’s another interesting thing: This answer is technically correct for what was asked, but the question and the answer are already as obsolete as the functions in question.

  • Just scoring the PHP version. In version 5.5 it became obsolete but still worked. It was removed in version 7.0.0. In its documentation it says: "This extension is obsolete since PHP 5.5.0 and has been removed in PHP 7.0.0." : link

  • @Christianoribeirosoares is a valid observation, but I hope you have noticed that the question and comments are from 2014 :D - however, I need to pass on some old answers to update. - grateful for the reminder

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

}


?>

Why using the mysql_ping() or the mysql_thread_id(), when the connection is closed, these commands return error because there is no Resource for them to work...

  • Mark Jorge’s answer as the correct one, so it signals to other users. Do not repeat the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.