How can PHP be used to store form data in a database and retrieve it for display on a webpage?
To store form data in a database using PHP, you can use SQL queries to insert the form data into a database table. To retrieve the stored data and display it on a webpage, you can use SQL queries to select the data from the database and then loop through the results to display them on the webpage.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert form data into database
$sql = "INSERT INTO form_data (name, email, message) VALUES ('John Doe', 'john.doe@example.com', 'Hello World')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Retrieve data from database and display on webpage
$sql = "SELECT * FROM form_data";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Email: " . $row["email"]. " - Message: " . $row["message"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
Related Questions
- Are there ways to prevent PHP files from being viewed via the URL to avoid unauthorized access to databases and sensitive information?
- How can the unnecessary use of conditional checks within loop count creation impact the readability and maintainability of PHP code?
- What are common issues encountered when using SSL with PHP SOAP?