Technology
How to Fetch Data from a Database in PHP and Display It in an HTML Form
How to Fetch Data from a Database in PHP and Display It in an HTML Form
Finding and displaying data from a database in a form using PHP is a common task in web development. This guide will walk you through the entire process using MySQL as the database. By the end, you will have a clear understanding of how to connect to a database, fetch data, and display it in an HTML form using PHP.
Step 1: Set Up Your Database Connection
The first step is to establish a connection to your MySQL database. In this example, we will use the mysqli extension for PHP.
connect_error) { die("Connection failed: " . $conn->connect_error); } ?>Step 2: Fetch Data from the Database
Once the connection is set up, you can use an SQL query to fetch the desired data from the database. In this case, let's assume you are fetching data from a table named users.
query($sql); if ($result->num_rows > 0) { // Fetch data into an associative array $data $result->fetch_all(MYSQLI_ASSOC); } else { $data []; // No data found } ?>Step 3: Display Data in an HTML Form
With the data fetched and stored in an associative array, you can now use HTML to create a form and loop through the data to display it.
Display Data in Form ID: Name: Email: Address: "; endforeach; ?>In this example, the form contains input fields that are pre-filled with the data fetched from the database. The disabled attribute ensures that the data cannot be modified in the form.
Step 4: Close the Database Connection
It is a good practice to close the database connection after you are done with your queries. This helps free up resources.
close(); ?>Summary
Connect to the Database: Use mysqli to establish a connection. Feth Data:
Use an SQL query to retrieve data from the database. Display in Form: Use HTML to create a form and loop through the fetched data to display it. Close Connection: Always close the database connection after you are done with your queries.Note
Ensure that you handle database connections and queries securely to prevent SQL injection, especially when accepting user input. This example assumes that the database structure is known and fields are predefined. Adjust the code as necessary based on your specific requirements.