What are the best practices for handling database connections in PHP scripts to avoid errors like "MySQL server has gone away"?
The "MySQL server has gone away" error occurs when a PHP script loses connection to the MySQL server due to inactivity or a timeout. To avoid this error, it is recommended to properly handle database connections by reconnecting if necessary before executing queries.
// Establish a database connection
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check if the connection is still active, and reconnect if necessary
if (!mysqli_ping($connection)) {
mysqli_close($connection);
$connection = mysqli_connect("localhost", "username", "password", "database");
}
// Execute your query using the $connection variable
$result = mysqli_query($connection, "SELECT * FROM table");
// Close the connection when finished
mysqli_close($connection);