What are best practices for handling MySQL connections in PHP scripts to avoid errors like the ones mentioned in the thread?

The best practice for handling MySQL connections in PHP scripts is to establish a connection only once and reuse it throughout the script. This can help avoid errors like "Too many connections" or "MySQL server has gone away" due to reaching the maximum number of connections or idle timeouts. One way to achieve this is by using a persistent connection or connection pooling.

// Establish a MySQL connection using PDO and store it in a variable
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => true));
    // Use $pdo for executing queries throughout the script
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}