What is the best practice for updating incomplete data entries in a MySQL database using PHP forms?
When updating incomplete data entries in a MySQL database using PHP forms, it is best practice to first retrieve the existing data for the entry, populate the form fields with this data, allow the user to make changes, and then update the database with the new data. This ensures that only the incomplete fields are updated while preserving the existing data.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if($connection === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Retrieve existing data for the entry
$id = $_GET['id'];
$query = "SELECT * FROM table_name WHERE id = $id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
// Display form with populated fields
echo "<form method='post' action='update.php'>";
echo "Name: <input type='text' name='name' value='" . $row['name'] . "'><br>";
echo "Email: <input type='email' name='email' value='" . $row['email'] . "'><br>";
echo "<input type='hidden' name='id' value='" . $id . "'>";
echo "<input type='submit' value='Update'>";
echo "</form>";
// Update database with new data
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$name = $_POST['name'];
$email = $_POST['email'];
$id = $_POST['id'];
$query = "UPDATE table_name SET name='$name', email='$email' WHERE id=$id";
if(mysqli_query($connection, $query)){
echo "Record updated successfully";
} else{
echo "ERROR: Could not able to execute $query. " . mysqli_error($connection);
}
}
// Close connection
mysqli_close($connection);
?>
Related questions
-
File uploads PHP storage
-
DOCTYPE declaration HTML documents PHP-generated pages
-
PHP CSS dynamic tables