PHP Function Reference

PHP mysqli ping() Method



The PHP mysqli::ping() / mysqli_ping() function is used to check whether the connection to the server is working. If it has gone down and global option mysqli.reconnect is enabled, an automatic reconnection is attempted.

Note: The php.ini setting mysqli.reconnect is ignored by the mysqlnd driver, so automatic reconnection is never attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

Syntax

//Object-oriented style
public mysqli::ping()

//Procedural style
mysqli_ping(mysql)

Parameters

mysql Required. For procedural style only: Specify a mysqli object returned by mysqli_connect() or mysqli_init().

Return Value

Returns true on success or false on failure.

Example: Object-oriented style

The example below shows the usage of mysqli::ping() method.

<?php
//establishing connection to the database
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

//checking if server is alive
if ($mysqli->ping()) {
  printf ("Connection is ok!\n");
} else {
  printf ("Error: %s\n", $mysqli->error);
}

//closing the connection
$mysqli->close();
?>

The output of the above code will be similar to:

Connection is ok!

Example: Procedural style

The example below shows the usage of mysqli_ping() function.

<?php
//establishing connection to the database
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

//checking if server is alive
if (mysqli_ping($mysqli)) {
  printf ("Connection is ok!\n");
} else {
  printf ("Error: %s\n", mysqli_error($mysqli));
}

//closing the connection
mysqli_close($mysqli);
?>

The output of the above code will be similar to:

Connection is ok!

❮ PHP MySQLi Reference