How can PHP be used to retrieve and display data from a database on the same page as a form?

To retrieve and display data from a database on the same page as a form in PHP, you can first connect to the database, query the data you want to display, and then populate the form fields with the retrieved data. You can achieve this by embedding PHP code within your HTML form to retrieve and display the data dynamically.

<?php
// Connect to database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Retrieve data from database
$sql = "SELECT * FROM table_name";
$result = mysqli_query($connection, $sql);

// Display form
echo "<form>";
while ($row = mysqli_fetch_assoc($result)) {
    echo "<input type='text' name='field_name' value='" . $row['column_name'] . "'><br>";
}
echo "<input type='submit' value='Submit'>";
echo "</form>";

// Close connection
mysqli_close($connection);
?>