Thursday, May 14, 2026
HomeLanguagesPHP | mysqli_ping() Function

PHP | mysqli_ping() Function

The mysqli_ping() function is used to ping a server connection. That is it is used to check if a host is reachable on an IP network or not. This function also tries to reconnect if an existing server connection is lost. To use this function, it is mandatory to first set up the connection with the MySQL database.
This function can be used in both Object Oriented and Procedural styles as described below: 

  • Object oriented style:
    Syntax:
ping();
  • Parameters: This function does not accepts any parameter, it is used with a connection instance.
    Return Value: This function returns True on success and False on failure.
    Below program illustrate the ping() function in object-oriented style:

PHP




<?php
$servername = "localhost";
$username = "username";
$password = "password";
 
// Creating a connection
$conn = new mysqli($servername, $username, $password);
 
// Check connection
if ($conn->connect_error) {
    die("Connection to the server failed: " . $conn->connect_error);
}
 
/* check if server is alive */
if ($conn->ping()) {
    printf ("Successful Connection!\n");
} else {
    printf ("Error: %s\n", $conn->error);
}
 
/* close connection */
$conn->close();
?>


  • Procedural style:
    Syntax:
mysqli_ping($conn);
  • Parameters: This function accepts a single parameter $conn which represents the connection to use.
    Return Value: This function returns True on success and False on failure.
    Below program illustrate the mysqli_ping() in the procedural style:

PHP




<?php
$$servername = "localhost";
$username = "username";
$password = "password";
 
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
 
// Checking connection
if (!$conn) {
    die("Connection to the server failed: " . mysqli_connect_error());
}
 
/* check if server is alive */
if (mysqli_ping($conn)) {
    printf ("Successful Connection!\n");
} else {
    printf ("Error: %s\n", mysqli_error($conn));
}
 
/* close connection */
mysqli_close($conn);
?>


Reference: http://php.net/manual/en/mysqli.ping.php

RELATED ARTICLES

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS