Home >Backend Development >PHP Tutorial >How do I fetch data from a database to form in PHP?

How do I fetch data from a database to form in PHP?

PHP中文网
PHP中文网forward
2024-11-21 10:43:24390browse

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[&#39;id&#39;]; ?>">     
<label for="name">Name:</label>     
<input type="text" id="name" name="name" value="<?php echo htmlspecialchars($user[&#39;name&#39;]); ?>">  
<label for="email">Email:</label>     
<input type="email" id="email" name="email" value="<?php echo htmlspecialchars($user[&#39;email&#39;]); ?>">          
<input type="submit" value="Update"> 
</form> 
<?php endif; ?>

Step 5: Close the Connection

<?php 
$conn->close(); 
?>

Explanation:

  • Database Connection: Replace localhost, username, password, and database_name with your actual database credentials.
  • SQL Query: Adjust the SQL query to fetch the data you need (e.g., by changing the WHERE clause).
  • HTML Form: The form fields are populated with the fetched data. Use htmlspecialchars() to prevent XSS attacks when displaying user input.
  • Form Submission: The form submits to update.php, where you would handle the form data for updating the database.

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!

Statement:
This article is reproduced at:quora.com. If there is any infringement, please contact admin@php.cn delete