How can multiple data records be updated in a MySQL database using PHP?
To update multiple data records in a MySQL database using PHP, you can use a loop to iterate through the records and execute an UPDATE query for each record. This can be achieved by fetching the records from the database, looping through them, and updating each record individually with the new data.
<?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);
}
// Fetch data records to be updated
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Update each record
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$newName = "New Name";
$newEmail = "newemail@example.com";
$updateSql = "UPDATE users SET name='$newName', email='$newEmail' WHERE id=$id";
$conn->query($updateSql);
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- Are there any specific best practices for beginners to follow when learning PHP?
- What are the performance implications of generating thumbnails for images in a PHP script for a photo gallery?
- What steps can be taken to ensure that all variables in a PHP script are properly utilized and displayed as intended?