What are the best practices for integrating HTML forms with a database in PHP to store user input within list items for future access?
To integrate HTML forms with a database in PHP to store user input within list items for future access, you can follow these best practices: 1. Create a database table to store the user input data, including a column for the list item content. 2. Use PHP to process the form submission and insert the user input into the database table. 3. Retrieve the stored data from the database and display it within list items on a webpage for future access.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "your_database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$list_item = $_POST["list_item"];
// Insert user input into the database
$sql = "INSERT INTO list_items (content) VALUES ('$list_item')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// Retrieve data from the database
$sql = "SELECT * FROM list_items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data in list items
while($row = $result->fetch_assoc()) {
echo "<li>" . $row["content"] . "</li>";
}
} else {
echo "0 results";
}
// Close database connection
$conn->close();
?>