What are some best practices for handling MySQL connections in PHP to avoid repetitive code?

When working with MySQL connections in PHP, it's best to create a separate function to handle the connection logic. This helps avoid repetitive code and ensures a consistent approach to managing connections throughout your application. By encapsulating the connection logic in a function, you can easily reuse it across different parts of your codebase.

<?php

function connectToMySQL(){
    $host = 'localhost';
    $username = 'root';
    $password = '';
    $database = 'my_database';

    $conn = new mysqli($host, $username, $password, $database);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    return $conn;
}

// To use the function:
$conn = connectToMySQL();
// Perform database operations using $conn

?>