How can PHP be used to automatically load previously entered data from a database into a form upon page reload?
To automatically load previously entered data from a database into a form upon page reload, you can query the database for the specific data based on a unique identifier (such as an ID) and then populate the form fields with the retrieved data. This can be achieved by embedding PHP code within the HTML form fields to set the values dynamically.
<?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);
}
// Query the database for the specific data
$id = $_GET['id']; // Assuming the ID is passed through the URL
$sql = "SELECT * FROM your_table WHERE id = $id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
}
?>
<form action="submit.php" method="post">
<input type="text" name="name" value="<?php echo $row['name']; ?>">
<input type="email" name="email" value="<?php echo $row['email']; ?>">
<textarea name="message"><?php echo $row['message']; ?></textarea>
<input type="submit" value="Submit">
</form>