What are some best practices for handling user input in PHP to prevent SQL injection attacks and ensure data integrity?

SQL injection attacks occur when malicious users input SQL queries into form fields, which can manipulate or access your database. To prevent this, always sanitize and validate user input before using it in SQL queries. Use prepared statements and parameterized queries to securely handle user input and ensure data integrity.

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

// Sanitize and validate user input
$username = $_POST['username'];
$password = $_POST['password'];

// Prepare a SQL statement using placeholders
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);

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

// Fetch the result
$result = $stmt->get_result();

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

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