What are the best practices for handling database connections and queries in PHP to avoid errors?

When handling database connections and queries in PHP, it is important to properly manage connections to avoid errors such as connection leaks or SQL injection attacks. To prevent these issues, it is recommended to use prepared statements with parameterized queries and to always close database connections after use.

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Prepare a SQL statement using a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Execute the query
$stmt->execute();

// Process the results

// Close the statement and connection
$stmt->close();
$conn->close();