How can PHP developers securely handle user input in forms to prevent SQL injection attacks and ensure data integrity in the database?

To securely handle user input in forms to prevent SQL injection attacks, PHP developers should use prepared statements with parameterized queries. This approach separates SQL logic from user input, preventing malicious input from being executed as SQL code. Additionally, developers should sanitize user input using functions like mysqli_real_escape_string() to ensure data integrity in the database.

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

// Prepare SQL statement with placeholders
$stmt = $mysqli->prepare("INSERT INTO users (username, email) VALUES (?, ?)");

// Bind parameters to placeholders
$stmt->bind_param("ss", $username, $email);

// Sanitize user input
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$email = mysqli_real_escape_string($mysqli, $_POST['email']);

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

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