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();