How can PHP be used to create a form that interacts with a database to display and update data?
To create a form that interacts with a database to display and update data using PHP, you would need to establish a connection to the database, retrieve the data to display in the form fields, and then update the database with the new data submitted through the form.
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Retrieve data from the database to display in the form fields
$sql = "SELECT * FROM table_name WHERE id = 1";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
// Update the database with new data submitted through the form
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$newData = $_POST['new_data'];
$updateSql = "UPDATE table_name SET column_name = '$newData' WHERE id = 1";
$conn->query($updateSql);
}
?>
<form method="post">
<input type="text" name="new_data" value="<?php echo $row['column_name']; ?>">
<input type="submit" value="Update">
</form>
Keywords
Related Questions
- What are the potential pitfalls of using nested sets in PHP, particularly in terms of reassigning numbers when adding or removing categories?
- How can one ensure that their server supports the commands required for specific PHP requests?
- What are the recommended methods for debugging cURL requests in PHP to ensure variables are passed correctly?