In this lesson, we will learn how we can fetch data from the database using PHP and display it in HTML form. We can do this by taking the following steps
title: "How to fetch data from the database in PHP and display in HTML form."
tags: html
canonical_url: https://kodlogs.com/blog/224/how-to-fetch-data-from-the-database-php-and-display-html-form
Create a database connection:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "demo";
$conn = mysqli_connect($host,$user,$pass, $db); // this will establish the connection with database
if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
?>
Retrieve the data from the database:
<?php
$sql = "select * from posts where id = 1"; // query to fetch the data form database
$rs = mysqli_query($conn, $sql);
$fetchRow = mysqli_fetch_assoc($rs); // this will return the result of specific row as an array
?>
HTML Form:
Now we will create the HTML form;
<html>
<head>
<title> Display data in html form </title>
<style>
body{font-family:verdana;}
.container{width:500px;margin: 0 auto;}
h3{line-height:20px;font-size:20px;}
input{display:block;width:350px;height:20px;margin:10px 0;}
textarea{display:block;width:350px;margin:10px 0;}
button{background:green; border:1px solid green;width:70px;height:30px;color:#ffffff}
</style>
</head>
<body>
<div class="container">
<h3>Add Post</h3>
<form action="" method="post">
<input type="text" name="title" value="<?php echo $fetchRow['post_title']?>" required>
<textarea cols="40" placeholder="Post Content" rows="8" name="post_content" required><?php echo $fetchRow['post_content']?></textarea>
<button type="submit" name="submit">Submit</button>
</form>
</div>
</body>
</html>
This is a very basic and simple example of fetching the data using the PHP script and display it in HTML form.
Top comments (0)