What are common pitfalls when establishing a connection to a MySQL database using PHP?

Common pitfalls when establishing a connection to a MySQL database using PHP include using incorrect credentials, not enabling the MySQL extension in PHP, and not handling connection errors properly. To solve these issues, make sure to double-check the database credentials, enable the MySQL extension in PHP configuration, and use error handling to catch any connection errors.

// Establish a connection to MySQL database
$servername = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";