How fetch data from database in php and display mysqli?

Updated on July 1, 2020

by Neeraj Agarwal

As we know Database is a collection of tables that stores data in it.

To retrieve or fetch data from MySQL database it is simple to do it using MySQL ” Select ” query in PHP .

Here in this blog post we will be going to see how to fetch data and to display it in front end.

MySQL Select Query:

SELECT column_name(s)
FROM table_name

PHP:

$query = mysql_query("select * from tablename", $connection);


For this you must have a database in MySQL . Here, we have a database named “company” which consists of a table named “employee” with 5 fields in it.

Next we have created a PHP page named “updatephp.php” where following steps will be going to perform:

  • We first establish connection with server .

$connection = mysql_connect("localhost", "root", "");

  • Selects database.

$db = mysql_select_db("company", $connection);

  • Executes MySQL select query.

$query = mysql_query("select * from employee", $connection);

  • Display fetched data

<span>Name:</span> <?php echo $row1['employee_name']; ?>
<span>E-mail:</span> <?php echo $row1['employee_email']; ?>
<span>Contact No:</span> <?php echo $row1['employee_contact']; ?>
<span>Address:</span> <?php echo $row1['employee_address']; ?>

  • Closing connection with server.

mysql_close($connection);


Below is our complete code with download and live demo option

How fetch data from database in php and display mysqli?


PHP File: readphp.php


<!DOCTYPE html>
<html>
<head>
<title>Read Data From Database Using PHP - Demo Preview</title>
<meta content="noindex, nofollow" name="robots">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="maindiv">
<div class="divA">
<div class="title">
<h2>Read Data Using PHP</h2>
</div>
<div class="divB">
<div class="divD">
<p>Click On Menu</p>
<?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server
$db = mysql_select_db("company", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from employee", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<b><a href="readphp.php?id={$row['employee_id']}">{$row['employee_name']}</a></b>";
echo "<br />";
}
?>
</div>
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query1 = mysql_query("select * from employee where employee_id=$id", $connection);
while ($row1 = mysql_fetch_array($query1)) {
?>
<div class="form">
<h2>---Details---</h2>
<!-- Displaying Data Read From Database -->
<span>Name:</span> <?php echo $row1['employee_name']; ?>
<span>E-mail:</span> <?php echo $row1['employee_email']; ?>
<span>Contact No:</span> <?php echo $row1['employee_contact']; ?>
<span>Address:</span> <?php echo $row1['employee_address']; ?>
</div>
<?php
}
}
?>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</div>
<?php
mysql_close($connection); // Closing Connection with Server
?>
</body>
</html>

MySQL Code Segment: Here is the MySQL code for creating database and table.


CREATE DATABASE company;
CREATE TABLE employee(
employee_id int(10) NOT NULL AUTO_INCREMENT,
employee_name varchar(255) NOT NULL,
employee_email varchar(255) NOT NULL,
employee_contact varchar(255) NOT NULL,
employee_address varchar(255) NOT NULL,
PRIMARY KEY (employee_id)
)

 CSS File: style.css


@import "http://fonts.googleapis.com/css?family=Droid+Serif";
/* Above line is to import google font style */
.maindiv {
margin:0 auto;
width:980px;
height:500px;
background:#fff;
padding-top:20px;
font-size:14px;
font-family:'Droid Serif',serif
}
.title {
width:100%;
height:70px;
text-shadow:2px 2px 2px #cfcfcf;
font-size:16px;
text-align:center;
font-family:'Droid Serif',serif
}
.divA {
width:70%;
float:left;
margin-top:30px
}
.form {
width:400px;
float:left;
background-color:#fff;
font-family:'Droid Serif',serif;
padding-left:30px
}
.divB {
width:100%;
height:100%;
background-color:#fff;
border:dashed 1px #999
}
.divD {
width:200px;
height:480px;
padding:0 20px;
float:left;
background-color:#f0f8ff;
border-right:dashed 1px #999
}
p {
text-align:center;
font-weight:700;
color:#5678C0;
font-size:18px;
text-shadow:2px 2px 2px #cfcfcf
}
.form h2 {
text-align:center;
text-shadow:2px 2px 2px #cfcfcf
}
a {
text-decoration:none;
font-size:16px;
margin:2px 0 0 30px;
padding:3px;
color:#1F8DD6
}
a:hover {
text-shadow:2px 2px 2px #cfcfcf;
font-size:18px
}
.clear {
clear:both
}
span {
font-weight:700
}

Conclusion:
We have shown you how SELECT command of SQL is executed with PHP, for fetching data from database. For more MySQL commands with PHP, follow our other blog posts .

40 Replies to “Retrieve or Fetch Data From Database in PHP”

  1. Dear,
    You have told how to create database and table in this example “Retreive Data From Database using PHP”, but forgot to tell how to make the entries into it…

    Reply

    1. Reply

  2. Its not working…..
    Some mistake is there in Retreive Data From Database using PHP

    Reply

    1. You can send us your query we’ll look into it

      Reply

    2. Hi Prakash , the below posted code is executed . just you change the database connection details as like your database.
      // see this code :
      ————————————–
      selectdata.php file
      ————————————

      Read Data From Database Using PHP – Demo Preview

      Read Data Using PHP

      Click On Menu
      <?php
      $connection = mysql_connect("localhost", "root", "[email protected]"); // Establishing Connection with Server
      $db = mysql_select_db("users", $connection); // Selecting Database
      //MySQL Query to read data
      $query = mysql_query("select * from employee", $connection);
      while ($row = mysql_fetch_array($query)) {
      echo "{$row[’employee_name’]}“;
      echo “”;
      }
      ?>

      —Details—

      Name:
      E-mail:
      Contact No:
      Address:

      ———————————————————
      css file :
      ————-

      @import “http://fonts.googleapis.com/css?family=Droid+Serif”;
      /* Above line is to import google font style */
      .maindiv {
      margin:0 auto;
      width:980px;
      height:500px;
      background:#fff;
      padding-top:20px;
      font-size:14px;
      font-family:’Droid Serif’,serif
      }
      .title {
      width:100%;
      height:70px;
      text-shadow:2px 2px 2px #cfcfcf;
      font-size:16px;
      text-align:center;
      font-family:’Droid Serif’,serif
      }
      .divA {
      width:70%;
      float:left;
      margin-top:30px
      }
      .form {
      width:400px;
      float:left;
      background-color:#fff;
      font-family:’Droid Serif’,serif;
      padding-left:30px
      }
      .divB {
      width:100%;
      height:100%;
      background-color:#fff;
      border:dashed 1px #999
      }
      .divD {
      width:200px;
      height:480px;
      padding:0 20px;
      float:left;
      background-color:#f0f8ff;
      border-right:dashed 1px #999
      }
      p {
      text-align:center;
      font-weight:700;
      color:#5678C0;
      font-size:18px;
      text-shadow:2px 2px 2px #cfcfcf
      }
      .form h2 {
      text-align:center;
      text-shadow:2px 2px 2px #cfcfcf
      }
      a {
      text-decoration:none;
      font-size:16px;
      margin:2px 0 0 30px;
      padding:3px;
      color:#1F8DD6
      }
      a:hover {
      text-shadow:2px 2px 2px #cfcfcf;
      font-size:18px
      }
      .clear {
      clear:both
      }
      span {
      font-weight:700
      }

      Reply

      1. I created a web page that take user detail and question and insert it into my database, but i can’t fetch the answer to back to their page without refreshing and update to keep sending back each answer to the question “id” can you please help me.
        This is for school test

        Reply

  3. How to use select button in php instead of names in your example Retreive Data From Database using PHP
    ?
    Please help me.

    Reply

  4. thanks buddy for your this Script i was lacking with only one line code which i have got now …

    Reply

    1. Thanks for your appreciation .!

      Keep reading your other blog posts.

      Reply

    2. Thanks for your appreciation .!

      Keep reading our other blog posts.

      Reply

  5. Thank you Admin
    very helpful

    Reply

    1. Hello Ajay,

      That sounds really great ! Keep reading our other blog posts for getting more coding tricks.

      Regards,
      FormGet Team

      Reply

  6. Admin please tell me
    What is db name , table name and its field name for “colorway.3.2.4” ?

    Reply

    1. It is a wordpress theme , if you have a wordpress site then you can install it to use , and rest you need not to create any database.

      Regards,
      FormGet Team.

      Reply

  7. If I select data from database, I want to get the related output from database. please solve this for me.

    Thanks to

    Admin

    Reply

    1. Actually the above tutorial is based upon what you are saying , isn’t it ?

      What else you wish to have changed in it ?

      Thanks & Regards,
      FormGet.com

      Reply

      1. Very helpfull!!! Thanx.

        Reply

    2. Thanks!!

      Reply

  8. How about retrieving image file from database?

    Reply

  9. Can we modify records from the database using the same form?
    The Insert and Retrieve parts work perfectly !
    Thank You.

    Reply

  10. when i click on link it is not showing details

    Reply

  11. Hey its a good example is it possible, like i want to create a page that shows up coming event “Event page” on my website from database, how can i do it?

    You can sent notes in my email add from above

    Reply

  12. it is good tutorial site and examples thank you formget team

    Reply

  13. in the row i can’t execute the data anyone can help me to solve this problem in my project..

    Reply

  14. yes, this is good tutorial for learning,… and i need one more help from you . as like this example , just create one menu bar (bredcrumb) and select one item in that. when i select one particular menu , those related information comes in to some other body div.. can you plz post this.
    Thanks in adavance.

    Reply

  15. How To Create customer profile using login session? the login session i use your login coding……. plzzz guide me…..

    Reply

  16. how to get image link to view the database

    Reply

  17. style=”font-family:Monospace;

    Reply

  18. hi. i am trying to design the data that i am selected it from the database in a table. what i want to know if i can add checkbox and button beside every row in php.
    echo “XXXXXXXXXXXXXXXXXXXXXXXXXXXXX”;
    while($row = $result->fetch_assoc()) {
    echo “”.$row[“XXXXXX”].””.$row[“XXXXXXXX”].””.$row[“XXXXXXX”].””.$row[“XXXXXXXx”].” “;
    how can i add to each one of these rows checkbox and button?

    Reply

  19. hi here u showed retrieve only one data stored in the db.how to design the table for displaying evryone’s information in one page

    Reply

  20. oh my god thank you so much it’s working. thankkkk you ..

    Reply

  21. Hello..can you help me on how to print/print preview the selected file? using this code or any other code i really need it for my project ..any help will be appreciated..Thank you.

    Reply

  22. while ($row = mysql_fetch_array($query)) has problems cause it indicates that the code expects parameter 1 but boolean given

    Reply

    1. Hi,

      Such error occurs usually when the mysql_query hasn’t run properly.
      Check whether mysql_query is executed properly and $query contains anything or not. The problem may be with the connection, query or it may be with the tables.

      So, make sure that your query must contain the same table name that you have created in your database. Also, check that the $query contains the results.

      Reply

  23. Such error occurs usually when the mysql_query hasn’t run properly.
    Check whether mysql_query is executed properly and $query contains anything or not. The problem may be with the connection, query or it may be with the tables.

    So, make sure that your query must contain the same table name that you have created in your database. Also, check that the $query contains the results.

    Reply

  24. Wonderful! Thankyou

    Reply

  25. Awesome tutorial. KEEP UP

    Reply

  26. hello admin..!
    i have created as you said above, but i’m unable to get the names in left side.
    there are no names, its not shows the database . but when i;m checks the database the data is there but its not showing. where to correct the code please help.

    Reply

  27. Very useful php data of your page, it’s most useful.

    Reply

  28. It’s really nice code, it’s working to use on my sample website.

    Reply

Leave a Reply

How do you fetch data from database in PHP and display in form MySQLi?

Connecting to a Database:.
MySQLi Object-Oriented $conn = new mysqli($servername, $username, $databasename).
MySQLi Procedural $conn = mysqli_connect($servername, $username, $password, $databasename);.
PDO. $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password, $databasename);.

How fetch data from database in PHP and display in PHP?

Retrieve or Fetch Data From Database in PHP.
SELECT column_name(s) FROM table_name..
$query = mysql_query("select * from tablename", $connection);.
$connection = mysql_connect("localhost", "root", "");.
$db = mysql_select_db("company", $connection);.
$query = mysql_query("select * from employee", $connection);.

How is data fetch from the database in PHP?

Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP function mysql_query. You have several options to fetch data from MySQL. The most frequently used option is to use function mysql_fetch_array(). This function returns row as an associative array, a numeric array, or both.

How can we fetch data from database in PHP and display in HTML?

Use the following steps for fetch/retrieve data from database in php and display in html table:.
Step 1 – Start Apache Web Server..
Step 2 – Create PHP Project..
Step 3 – Execute SQL query to Create Table..
Step 4 – Create phpmyadmin MySQL Database Connection File..
Step 5 – Create Fetch Data PHP File From Database..