How can PHP be used to update specific user data in a database based on user input?
To update specific user data in a database based on user input, you can use PHP to retrieve the user input, validate it, and then update the corresponding record in the database using SQL queries. Make sure to sanitize the user input to prevent SQL injection attacks.
<?php
// Retrieve user input
$user_id = $_POST['user_id'];
$new_data = $_POST['new_data'];
// Validate user input
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Update user data in the database
$sql = "UPDATE users SET data = '$new_data' WHERE id = $user_id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Keywords
Related Questions
- What are best practices for including PHP code within HTML files, especially in the <head> section?
- What considerations should be taken into account when evaluating the user input from dynamically generated checkboxes in a PHP application?
- How can brute-force methods be avoided when calculating date differences in PHP, especially when dealing with weekends?