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

When connecting to a MySQL database using PHP, it is essential to follow best practices to ensure the security of the connection. This includes using prepared statements to prevent SQL injection attacks, storing database credentials securely, and validating user input before executing queries.

<?php
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

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

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

// Use prepared statements to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

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