How can dynamic queries be used in PHP to update database records based on user input?
Dynamic queries in PHP can be used to update database records based on user input by constructing SQL queries using user-provided data. This can be achieved by sanitizing and validating user input to prevent SQL injection attacks. The user input can then be used to dynamically build and execute UPDATE queries to modify the database records accordingly.
// Assuming $conn is the database connection object
// Sanitize and validate user input
$user_id = $_POST['user_id'];
$new_name = mysqli_real_escape_string($conn, $_POST['new_name']);
// Construct and execute dynamic update query
$sql = "UPDATE users SET name = '$new_name' WHERE id = $user_id";
if(mysqli_query($conn, $sql)){
echo "Record updated successfully";
} else{
echo "Error updating record: " . mysqli_error($conn);
}
Keywords
Related Questions
- Are there any best practices for increasing security when handling passwords in PHP?
- How can the code be modified to ensure that the actual file name is passed to the database instead of the word "Array"?
- What potential pitfalls should be considered when parsing data from external websites in PHP scripts?