What are the best practices for securing PHP code that interacts with a MySQL database to prevent SQL injection vulnerabilities?

SQL injection vulnerabilities can occur when user input is not properly sanitized before being used in SQL queries, allowing malicious users to manipulate the queries and potentially access or modify sensitive data in the database. To prevent SQL injection attacks in PHP code that interacts with a MySQL database, it is important to use prepared statements with parameterized queries. This ensures that user input is treated as data rather than executable code, making it impossible for attackers to inject SQL commands.

// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Sanitize user input before binding it to the query
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);

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

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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