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();
Keywords
Related Questions
- What could be causing the error message "Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource" in PHP?
- How can test scripts be effectively used in PHP to verify the functionality and output of code snippets or functions?
- What are the potential pitfalls of using PHP to generate HTML content, and how can they be avoided?