How can PHP be used to filter and sanitize form data before storing it in a database to prevent SQL injection attacks?

To prevent SQL injection attacks, form data can be filtered and sanitized in PHP before storing it in a database. This can be done by using functions like mysqli_real_escape_string() to escape special characters, validating input fields to ensure they meet expected formats, and using prepared statements to bind parameters securely.

// Assuming $conn is the database connection

// Filter and sanitize form data
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$age = filter_var($_POST['age'], FILTER_SANITIZE_NUMBER_INT);

// Prepare SQL statement with placeholders
$stmt = $conn->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");
$stmt->bind_param("ssi", $name, $email, $age);

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

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