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

One common pitfall when establishing a connection to a database in PHP is not handling errors properly. It is important to check for connection errors and handle them gracefully to prevent potential issues. Another pitfall is not securely storing database credentials, which can lead to security vulnerabilities. Make sure to store credentials in a secure manner, such as using environment variables.

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

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

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