What are some best practices for securely connecting to and querying a MySQL database using PHP?

When connecting to a MySQL database using PHP, it is important to ensure that the connection is secure to prevent potential security vulnerabilities. One best practice is to use parameterized queries to prevent SQL injection attacks. Additionally, it is recommended to use secure connection methods such as SSL to encrypt the data being transmitted between the PHP application and the MySQL database.

<?php
// MySQL database credentials
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";

// Create a secure connection to the MySQL database
$conn = new mysqli($servername, $username, $password, $database);

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

// Example of a parameterized query to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

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

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