How can PHP be used to modify data from other users in a database?
To modify data from other users in a database using PHP, you can first retrieve the data based on the user's ID, then update the specific fields with the new values. It's important to validate the user's permissions before allowing any modifications to take place.
<?php
// 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);
}
// Retrieve data based on user ID
$user_id = 123;
$sql = "SELECT * FROM users WHERE id = $user_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Update specific fields with new values
$new_name = "John Doe";
$new_email = "john.doe@example.com";
$update_sql = "UPDATE users SET name = '$new_name', email = '$new_email' WHERE id = $user_id";
if ($conn->query($update_sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
} else {
echo "User not found";
}
$conn->close();
?>
Related Questions
- How can PHP be utilized to create interactive features within a learning program, such as quizzes or exams?
- What are the advantages of using a dedicated mailer class like Swift Mailer for sending emails in PHP?
- What are some common challenges faced by beginners when trying to integrate PHP and JavaScript for dynamic web development tasks?