What are the best practices for sanitizing user input in PHP to prevent SQL injection attacks?

To prevent SQL injection attacks in PHP, it is essential to sanitize user input before using it in database queries. One common approach is to use prepared statements with parameterized queries, which separate the SQL code from the user input. Another method is to use functions like mysqli_real_escape_string() to escape special characters in user input before inserting it into SQL queries.

// Using prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

if ($stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?")) {
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        // Process the results
    }
    $stmt->close();
}
$mysqli->close();