How can a new form with pre-filled data from a database be generated based on search results in PHP?
To generate a new form with pre-filled data from a database based on search results in PHP, you can first fetch the data from the database based on the search query. Then, you can populate the form fields with the retrieved data using PHP. Finally, display the form with the pre-filled data to the user for editing or submission.
<?php
// Assume $searchQuery contains the search query input
// Fetch data from the database based on the search query
// Populate form fields with the retrieved data
// Example code to fetch data from a MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM your_table WHERE column_name = '$searchQuery'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$field1 = $row['field1'];
$field2 = $row['field2'];
// Populate other form fields as needed
}
}
$conn->close();
?>
<form method="post" action="submit.php">
<input type="text" name="field1" value="<?php echo $field1; ?>">
<input type="text" name="field2" value="<?php echo $field2; ?>">
<!-- Add other form fields here -->
<button type="submit">Submit</button>
</form>
Related Questions
- How can developers avoid potential pitfalls or compatibility issues when using CSS properties like table-layout in PHP projects?
- What are some common pitfalls when using preg_match in PHP, especially when trying to match specific patterns like an 8-digit number?
- How can PHP be used to filter out empty columns from a database query result set?