What are common errors when setting up a MySQL connection in PHP and how can they be avoided?

Common errors when setting up a MySQL connection in PHP include using incorrect credentials, not enabling the MySQL extension in PHP configuration, and not specifying the correct host or port. To avoid these errors, double-check your database credentials, ensure the MySQL extension is enabled in your PHP configuration, and verify the host and port settings.

// Correct way to set up a MySQL connection in PHP
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";

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

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