In the context of PHP, what are some best practices for handling SQL injections in code that involves database interactions?

SQL injection is a common security vulnerability where attackers can manipulate SQL queries by inserting malicious code. To prevent SQL injection, it's essential to use parameterized queries or prepared statements in PHP when interacting with databases. This approach ensures that user input is properly sanitized and treated as data rather than executable code.

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

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

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

// Set the username variable from user input
$username = $_POST['username'];

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

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Output the results
}

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