What are common reasons for MySQL connection errors in PHP scripts?

Common reasons for MySQL connection errors in PHP scripts include incorrect database credentials, server connectivity issues, and insufficient permissions. To solve this issue, double-check the database host, username, password, and database name in your connection script. Ensure that the MySQL server is running and accessible from the PHP server. Additionally, make sure that the user account used to connect has the necessary permissions to access the database.

<?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";
?>