downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

mysql_query> <mysql_pconnect
[edit] Last updated: Fri, 25 May 2012

view this page in

mysql_ping

(PHP 4 >= 4.3.0, PHP 5)

mysql_pingEfectuar un chequeo de respuesta (ping) sobre una conexión de servidor o reconectarse si no hay conexión

Descripción

bool mysql_ping ([ resource $link_identifier = NULL ] )

Chequea si está activa o no la conexión con el servidor. Si ésta se ha caído, una reconexión automática es intentada. Esta función puede ser usada por scripts que permanecen pasivos durante largos espacios de tiempo, para chequear si el servidor ha cerrado la conexión, y reconectarse de ser necesario.

Nota:

A partir de MySQL 5.0.13, la característica de reconexión automática se encuentra deshabilitada.

Parámetros

link_identifier

La conexión MySQL. Si el identificador de enlace no se especifica, el último enlace abierto por mysql_connect() es asumido. Si no se encuentra dicho enlace, la función intentará establecer un nuevo enlace como si mysql_connect() fuese invocado sin parámetros. Si no se encuentra o establece una conexión, un error de nivel E_WARNING es generado.

Valores devueltos

Devuelve TRUE si la conexión con el servidor MySQL está funcionando, o FALSE de lo contrario.

Ejemplos

Ejemplo #1 Un ejemplo de mysql_ping()

<?php
set_time_limit
(0);

$con mysql_connect('localhost''mysqlusuario''mypassword');
$bd  mysql_select_db('mi_bd');

/* Asumiendo que esta consulta toma mucho tiempo */
$resultado mysql_query($sql);
if (!
$resultado) {
    echo 
'La consulta #1 falló, saliendo.';
    exit;
}

/* Asegurarse de que la conexión sigue viva, si no, intentar una
   re-conexión */
if (!mysql_ping($con)) {
    echo 
'Se ha perdido la conexión, saliendo después de la consulta #1';
    exit;
}
mysql_free_result($result);

/* Ya que la conexión sigue viva, corramos otra consulta */
$resultado2 mysql_query($sql2);
?>

Ver también



mysql_query> <mysql_pconnect
[edit] Last updated: Fri, 25 May 2012
 
add a note add a note User Contributed Notes mysql_ping
Doug 19-Apr-2010 08:24
This function *does not* attempt to reconnect at this time.  It only tells you whether or not you currently *are* connected.

To actually reconnect, you will have to implement this yourself in a wrapper class.
alext at marketdream dot com dot mx 29-Sep-2009 08:28
mysql_ping() is really helpful when you have this annoying error:

MYSQL Error 2006 Server has gone away

For CI users:
In 1.7.2 version of codeigniter, there is a function

$this->db->reconnect()

that uses mysql_ping() to reestablish the timed out connection.

This function is specially useful when developing social media sites that uses hundreds of connections to the db such asinserting or selecting.
luky37 03-Feb-2009 11:15
If you get 'error 2006: MySQL server has gone away' messages when running (really) long scripts, mysql_ping will help detecting the loss of the db-connection. This can happen, when 'wait timeout' is reached (MySQL default is 8 hours).
oscar at bitagenda dot com 02-Oct-2007 04:10
Very confusing description.
... If it has gone down, an automatic reconnection is attempted
 (But the function returns only true or false, so if you have variable say $link = connection resource, it will be an invalid resource)

Then ...
... Note:  Since MySQL 5.0.13, automatic reconnection feature is disabled.

OK, if it returns false, I have the chance to reconnect updating my resource variable
$link = reconnect

But I did called the function with $link to do the check, so ...
If no such link is found, it will try to create one as if mysql_connect() was called with no arguments (this are  different arguments than automatic reconnection, doesn't it? I think, automatic reconnecting, say to $link, would be with its own arguments previously used to create the connection)

So bad decision about automatic recconection feature disabled ...

At least the function should have the param by reference, so in case it reconnects with a new link_identifier.

bool mysql_ping ( &[resource $link_identifier] )

Or a return value of link_identifier, not true.

if ($link=mysql_ping($link)) {...} else { whatever }
miro dot dietiker at md-systems dot ch 31-Aug-2007 11:32
When checking if a $resource works...
be prepared that mysql_ping returns NULL as long as $resource is no correct mysql resource.
<?php
$resource
=NULL;
var_dump = @mysql_ping($resource);
# showing NULL
?>
This could be used to decide of a current $resource is a mysql or a mysqli connection when nothing else is available to do that...
dustin hawkins 31-Jul-2006 12:32
When using the mysql_ping command under php 5.1.2 and mysql 5.0, I was having problems with the auto-reconnect "feature", mainly that when the connection was severed, a mysql_ping would not automatically re-establish the connection to the database.

The connection to the DB is dropped when the time without a query excedes the wait_timeout value in my.cnf. You can check your wait_timeout by running the query "SHOW VARIABLES;"

If you're having problems auto-reconnecting when the connection is dropped, use this code:

<?php

$conn
= mysql_connect('localhost','user','pass');
mysql_select_db('db',$conn);

if (!
mysql_ping ($conn)) {
  
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
  
mysql_close($conn);
  
$conn = mysql_connect('localhost','user','pass');
  
mysql_select_db('db',$conn);
}

//run queries knowing that your connection is alive....

?>
cybot2000 at yahoo dot de 25-May-2005 04:44
It should be noted that mysql_ping() seems to reset the error message on the server.
I used it to check whether the connection was still alive before reading the error message via mysql_error() and it always returned an empty string. Upon removing the connection check everything worked.
vinicius at teracom dot com dot br 16-Mar-2004 07:35
Is important to remember that if your first connection to mysql don't works, mysql_ping will always return true! So, if you want to check if mysql is connected, first of all you must check if mysql_connect do not returns false and then you can begin to check mysql_ping.

 
show source | credits | sitemap | contact | advertising | mirror sites