PHP 8.3.4 Released!

mysql_ping

(PHP 4 >= 4.3.0, PHP 5)

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

Advertencia

Esta extensión fue declarada obsoleta en PHP 5.5.0 y eliminada en PHP 7.0.0. En su lugar debería utilzarse las extensiones MySQLi o PDO_MySQL. Véase también la guía MySQL: elegir una API. Las alternativas a esta función son:

Descripción

mysql_ping(resource $link_identifier = NULL): bool

Chequea si está activa o no la conexión con el servidor. Si ésta se ha caído, se intenta una reconexión automática. 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:

La reconexión automática está deshabilitada de forma predeterminada en versiones de MySQL >= 5.0.3.

Parámetros

link_identifier

La conexión MySQL. Si no se especifica el identificador de enlace, se asume el último enlace abierto por mysql_connect(). Si no se encuentra este enlace, se intentará crear un nuevo enlace como si mysql_connect() hubiese sido invocada sin argumentos. Si no se encuentra o establece ninguna conexión, se genera un error de nivel E_WARNING.

Valores devueltos

Devuelve true si la conexión con el servidor MySQL está funcionando, o false si no.

Ejemplos

Ejemplo #1 Un ejemplo de mysql_ping()

<?php
set_time_limit
(0);

$conexión = mysql_connect('localhost', 'usuario_mysql', 'contraseña');
$bd = mysql_select_db('mi_bd');

/* Se asume 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 reconexión */
if (!mysql_ping($conexión)) {
echo
'Se ha perdido la conexión, saliendo después de la consulta #1';
exit;
}
mysql_free_result($resultado);

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

Ver también

add a note

User Contributed Notes 7 notes

up
3
cybot2000 at yahoo dot de
18 years ago
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.
up
3
alext at marketdream dot com dot mx
14 years ago
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.
up
2
miro dot dietiker at md-systems dot ch
16 years ago
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...
up
2
Doug
13 years ago
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.
up
2
dustin hawkins
17 years ago
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....

?>
up
2
vinicius at teracom dot com dot br
20 years ago
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.
up
-3
luky37
15 years ago
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).
To Top