Home >Backend Development >PHP Tutorial >How do I fetch data from a database to form in PHP?
To fetch data from a database in PHP and display it in a form, you'll typically follow these steps:
Connect to the Database: Establish a connection to your database using MySQLi or PDO.
Query the Database: Execute a SQL query to retrieve the desired data.
Fetch the Data: Retrieve the data from the query result.
Populate the Form: Use the fetched data to fill in the form fields.
Here’s a simple example using MySQLi:
Step 1: Connect to the Database
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
Step 2: Query the Database
<?php $sql = "SELECT id, name, email FROM users WHERE id = 1"; // Example query $result = $conn->query($sql); ?>
Step 3: Fetch the Data
<?php $user = null; if ($result->num_rows > 0) { // Fetch associative array $user = $result->fetch_assoc(); } else { echo "No results found."; } ?>
Step 4: Populate the Form
<?php if ($user): ?> <form action="update.php" method="post"> <input type="hidden" name="id" value="<?php echo $user['id']; ?>"> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($user['name']); ?>"> <label for="email">Email:</label> <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>"> <input type="submit" value="Update"> </form> <?php endif; ?>
Step 5: Close the Connection
<?php $conn->close(); ?>
Explanation:
This example gives you a basic structure to fetch and display data in a form using PHP. Adjust the SQL query and form fields as necessary for your application.
The above is the detailed content of How do I fetch data from a database to form in PHP?. For more information, please follow other related articles on the PHP Chinese website!