What are some common errors or pitfalls when using PHP to connect to a database?

One common error when connecting to a database in PHP is not properly handling connection errors. It is important to check for connection errors and handle them gracefully to prevent unexpected behavior in your application. Another pitfall is not sanitizing user input before using it in database queries, which can lead to SQL injection attacks. Always use prepared statements or parameterized queries to prevent this security risk.

// Correct way to connect to a database in 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);
}