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

When handling database connections and queries in PHP, it is important to use prepared statements with parameterized queries to prevent SQL injection attacks. Additionally, always validate and sanitize user input before using it in a query to avoid potential security vulnerabilities.

// Establish a secure 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);
}

// Use prepared statements with parameterized queries
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Sanitize user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);

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

// Process the results
while ($row = $result->fetch_assoc()) {
    // Handle the retrieved data
}

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