How can you update a specific row in a database table with user input in PHP?
To update a specific row in a database table with user input in PHP, you can use a SQL UPDATE query with user input as parameters. Make sure to sanitize and validate the user input to prevent SQL injection attacks. You can use prepared statements to safely insert user input into the query.
<?php
// Assuming you have already established a database connection
// Get user input
$user_id = $_POST['user_id'];
$new_value = $_POST['new_value'];
// Prepare and execute the SQL UPDATE query
$stmt = $pdo->prepare("UPDATE table_name SET column_name = :new_value WHERE user_id = :user_id");
$stmt->bindParam(':new_value', $new_value);
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
// Check if the query was successful
if ($stmt->rowCount() > 0) {
echo "Row updated successfully.";
} else {
echo "Failed to update row.";
}
?>
Keywords
Related Questions
- What are potential reasons for a PHP session to be lost during redirection?
- When using a template engine like Smarty in PHP, what is the correct syntax for displaying a variable, and how does it impact the integration of JavaScript within the template?
- What are the recommended methods for organizing and structuring PHP code to improve readability and maintainability in a CMS application?