What are common errors or pitfalls to avoid when connecting to a MySQL database in PHP?

One common error when connecting to a MySQL database in PHP is using incorrect credentials, such as the wrong username or password. To avoid this, double-check your credentials and ensure they match the ones set up for your MySQL database. Additionally, make sure the MySQL server is running and accessible from your PHP script.

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydatabase";

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

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