In the provided PHP script, what improvements can be made to ensure the proper handling of form submissions and database updates?
The provided PHP script lacks proper validation and sanitization of user input, leaving it vulnerable to SQL injection attacks. To ensure the proper handling of form submissions and database updates, we should use prepared statements to prevent SQL injection and validate user input to ensure it meets the required criteria.
<?php
// Validate and sanitize user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
if ($name && $email) {
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare SQL statement
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
// Execute the statement
$stmt->execute();
// Check if the query was successful
if ($stmt->affected_rows > 0) {
echo "User added successfully";
} else {
echo "Error adding user";
}
// Close the statement and connection
$stmt->close();
$conn->close();
} else {
echo "Invalid input";
}
?>
Related Questions
- What best practice should the user follow when handling form actions in PHP scripts to avoid parameter overwriting?
- What are the advantages of using absolute paths over relative paths in HTML when dealing with downloads in PHP?
- In the context of PHP file manipulation, what are some recommended approaches for troubleshooting errors related to file operations?