What are best practices for displaying and updating database records in PHP forms?
When displaying and updating database records in PHP forms, it is important to follow best practices to ensure data integrity and security. One common approach is to retrieve the record from the database based on a unique identifier, display the existing data in the form fields, allow users to make changes, validate the input, and then update the database with the new information.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve record based on unique identifier
$id = $_GET['id'];
$sql = "SELECT * FROM records WHERE id = $id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
// Display form with existing data
?>
<form method="post" action="update.php">
<input type="text" name="name" value="<?php echo $row['name']; ?>">
<input type="email" name="email" value="<?php echo $row['email']; ?>">
<input type="submit" value="Update">
</form>
<?php
} else {
echo "Record not found";
}
$conn->close();
?>