Skip to content
PHP Logo

How can the code snippet be modified to ensure proper editing of user details in the database?

The issue with the current code snippet is that it is vulnerable to SQL injection attacks as it directly concatenates user input into the SQL query. To ensure proper editing of user details in the database, we need to use prepared statements with parameterized queries to prevent SQL injection attacks.

php
// Ensure proper editing of user details in the database using prepared statements

// Assume $conn is the database connection

if(isset($_POST['edit_user'])) {
    $user_id = $_POST['user_id'];
    $username = $_POST['username'];
    $email = $_POST['email'];

    $stmt = $conn->prepare("UPDATE users SET username = ?, email = ? WHERE user_id = ?");
    $stmt->bind_param("ssi", $username, $email, $user_id);

    if($stmt->execute()) {
        echo "User details updated successfully";
    } else {
        echo "Error updating user details: " . $conn->error;
    }

    $stmt->close();
}