How can PHP effectively handle form submissions to update specific database entries based on user input?
To handle form submissions to update specific database entries based on user input, PHP can utilize SQL queries to update the database with the new information provided by the user. This involves capturing the input data from the form, sanitizing it to prevent SQL injection attacks, and then executing an UPDATE query to modify the corresponding database entries.
<?php
// Assuming form data is submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
// Sanitize input data
$input1 = htmlspecialchars($input1);
$input2 = htmlspecialchars($input2);
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Update specific database entries based on user input
$sql = "UPDATE table_name SET column1 = '$input1', column2 = '$input2' WHERE condition";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
// Close database connection
$conn->close();
}
?>