What are common causes of MySQL connection errors in PHP scripts?

Common causes of MySQL connection errors in PHP scripts include incorrect database credentials, server connectivity issues, and insufficient permissions for the user. To solve this issue, double-check the database credentials, ensure the server is running and accessible, and grant the necessary permissions to the user.

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