W3docs

ping

In this article, we will focus on the mysqli_ping() function in PHP, which is used to check if a connection to the MySQL server is active.

In this article, we will focus on the mysqli_ping() function in PHP, which is used to check if a connection to the MySQL server is active.

Introduction to the mysqli_ping() function

The mysqli_ping() function is a built-in PHP function that checks whether a connection to the MySQL server is still active. It returns a boolean value: true if the connection is alive, or false otherwise. If the connection has been lost, mysqli_ping() attempts to reconnect, provided the reconnect property is enabled (which is true by default).

How to use the mysqli_ping() function

Using the mysqli_ping() function is straightforward. Here's an example:

How to use the mysqli_ping() function

<?php
$mysqli = new mysqli("localhost", "username", "password", "database");

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
    exit();
}

// ping() automatically attempts to reconnect if the link is dead
if ($mysqli->ping()) {
    echo "Connection is OK!";
} else {
    echo "Error: " . $mysqli->error;
}

$mysqli->close();
?>

The script initializes a MySQLi connection, verifies it succeeded via connect_errno, and then calls ping() to confirm the link is alive. It outputs a success or error message accordingly.

Security Note: In production environments, avoid hardcoding database credentials. Use environment variables or secure configuration files to store sensitive data.

For procedural style, you can use mysqli_ping($link) instead:

<?php
$link = mysqli_connect("localhost", "username", "password", "database");

if (!$link) {
    die("Connection failed: " . mysqli_connect_error());
}

if (mysqli_ping($link)) {
    echo "Connection is OK!";
} else {
    echo "Error: " . mysqli_error($link);
}

mysqli_close($link);
?>

Conclusion

In conclusion, the mysqli_ping() function is a powerful tool for checking if a connection to the MySQL server is active. By understanding how to use the function, you can ensure that your PHP application is always connected to the MySQL server and avoid any issues that may arise from a lost connection.

Practice

Practice

What is the purpose of a ping in PHP?