Open In App

How to fetch data from Database in PHP PDO using loop ?

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The PDO (PHP Data Objects) defines the lightweight, consistent interface for accessing databases in PHP. 

Approach: Make sure you have XAMPP or WAMP installed on your windows machine. In case you’re using Linux then install the LAMP server. In this article, we will be using the XAMPP server.

Follow the steps to fetch data from the Database in PHP PDO: 

1. Create Database: Create a database using XAMPP, the database is named “geeksforgeeks” here. You can give any name to your database. 

create database “geeksforgeeks”

2. Create Table: Create a table named “fetch_record” with 2 columns to store the data.

create table “fetch_record”

3. Create Table Structure: The table “fetch_record” contains 2 fields.

  • id – primary key – auto increment
  • studentname – varchar(100)

The datatype for studentname is varchar. The size can be altered as per the requirement. However, 100 is sufficient, and the datatype for “id” is int and it is a primary key. Set the primary key to auto-increment, so that the value of id increase automatically. A primary key also called a primary keyword, is a key in a relational database that is unique for each record. It is a unique identifier, such as a driver’s license number, telephone number (including area code), or vehicle identification number (VIN). 

To create a table copy and paste the following code into the SQL panel of your PHPMyAdmin.

DROP TABLE IF EXISTS `fetch_record`;
CREATE TABLE IF NOT EXISTS `fetch_record` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`studentname` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

To do this from SQL Panel refer to the following screenshot.

create a table from SQL panel

The structure of the table will look like this 

table structure

4. Insert student record: Here I have only taken the name and id of students. You can add more fields, according to your requirements. 

Copy and paste the following code into the SQL panel of your PHPMyAdmin.

INSERT INTO `fetch_record` (`id`, `studentname`) VALUES (NULL, 'Neha'), (NULL, 'Honey'), (NULL, 'Amulaya Sharma'), 
(NULL, 'Kajal Singhal'), (NULL, 'Neeraj Pandey'), (NULL, 'Nikhil Kumar');

insert records

After inserting the information, the table will look like this. 

table records

5. Create a folder “fetch”, that includes the two following files: The folder should be in “C:\xampp\htdocs\” (or where your XAMPP is installed). 

5.1. index.php: Here foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)
statement

foreach (array_expression as $key => $value)
statement

The following SQL query is used to fetch all data from the table.

SELECT * FROM fetch_record;

Example: 

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
 
    <link rel="stylesheet" href=
    <title>Attendance Page</title>
</head>
 
<body>
    <div class="container">
        <div class="row">
            <h2>Attendance</h2>
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Sno.</th>
                        <th>Student Name</th>
                        <th>Attendance</th>
                    </tr>
                </thead>
 
                <tbody>
                    <?php
                        include_once('connection.php');
                        $a=1;
                        $stmt = $conn->prepare(
                                "SELECT * FROM fetch_record");
                        $stmt->execute();
                        $users = $stmt->fetchAll();
                        foreach($users as $user)
                        {
                    ?>
                    <tr>
                        <td>
                            <?php echo $user['id']; ?>
                        </td>
                        <td>
                            <?php echo $user['studentname']; ?>
                        </td>
 
                        <td>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input"
                                        type="radio" name="''"
                                         
                                        id="inlineRadio1"
                                    value="'..$a..'">
                                <label class="form-check-label"
                                    for="inlineRadio1">A</label>
                            </div>
 
                            <div class="form-check form-check-inline">
                                <input class="form-check-input"
                                    type="radio" name="'..$a..'"
                                    id="inlineRadio2" value="option2">
 
                                <label class="form-check-label"
                                    for="inlineRadio2">P</label>
                            </div>
                        </td>
                    </tr>
                    <?php
                    }
                    ?>
                </tbody>
            </table>
 
            <input class="btn btn-primary"
                    type="submit" value="Submit">
        </div>
    </div>
</body>
 
</html>


5.2. connection.php: 

PHP




<?php
 
$conn = "";
 
try {
    $servername = "localhost:3306";
    $dbname = "geeksforgeeks";
    $username = "root";
    $password = "";
 
    $conn = new PDO(
        "mysql:host=$servername; dbname=$dbname;",
        $username, $password
    );
     
    $conn->setAttribute(PDO::ATTR_ERRMODE,
                PDO::ERRMODE_EXCEPTION);
     
} catch(PDOException $e) {
    echo "Connection failed: "
        . $e->getMessage();
}
 
?>


6. After completing all these steps, now do the following steps:

  1. Run XAMPP
  2. Start Apache server and MySQL
  3. Type http://localhost/fetchData/dashboard.php in your browser.

The table will look like this and that’s how you fetch the information from the Database in PHP PDO.

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Similar Reads

Create a chart from JSON data using Fetch GET request (Fetch API) in JavaScript
In this article, we are going to create a simple chart by fetching JSON Data using Fetch() method of Fetch API. The Fetch API allows us to conduct HTTP requests in a simpler way. The fetch() method: The fetch method fetches a resource thereby returning a promise which is fulfilled once the response is available. Syntax: const response = fetch(resou
3 min read
How to upload images in MySQL using PHP PDO ?
In this article, we will upload images to the MySQL database using PHP PDO and display them on the webpage. Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this tutorial, we will be using the WAMP server. Article content: Table StructureDatabase configuration using PDO.HTML &amp; PHP FilesWorking ProcedureCo
5 min read
How to fetch data from localserver database and display on HTML table using PHP ?
In this article, we will see how we can display the records in an HTML table by fetching them from the MySQL database using PHP. Approach: Make sure you have XAMPP or WAMP server installed on your machine. In this article, we will be using the WAMP server. WAMP Server is open-source software for the Microsoft Windows operating system, developed by
4 min read
PHP program to fetch data from localhost server database using XAMPP
In this article, we will see how we can display the records by fetching them from the MySQL database using PHP.  Approach: Make sure you have an XAMPP server or WAMP server installed on your machine. In this article, we will be using the XAMPP server. XAMPP is a free and open-source cross-platform web server solution stack package developed by Apac
4 min read
What is PDO in PHP ?
In this article, we will discuss PDO in PHP in detail. There are three main options for C/C++ Code &lt;?php try { $dbhost = 'localhost'; $dbname='gfg'; $dbuser = 'root'; $dbpass = ''; $connect = new PDO( &quot;mysql:host=$dbhost;dbname=$dbname&quot;, $dbuser, $dbpass); } catch (PDOException $e) { echo &quot;Error : &quot; . $e-&gt;getMessage() .
4 min read
How to fetch data from the database in PHP ?
Database operations in PHP are a very crucial thing that is especially needed in CRUD (Create, Read, Update and Delete) operations. In this article, we will discuss the Read part i.e. data fetching from database. There are two ways to connect to a database using PHP. They are as follows. MySQLi ("i" stands for improved)PDO (PHP Data Objects) MySQLi
4 min read
What is the difference between react-fetch and whatwg-fetch in React.js ?
React-fetch and Whatwg-fetch are both libraries for making HTTP requests in a React application, but they are used for different purposes and have different features. Table of Content React-fetchWhatwg-fetchDifference between React-fetch and Whatwg-fetchReact-fetch: `react-fetch` is a library offering a higher-order component (HOC) for streamlined
2 min read
How to Fetch XML with Fetch API in JavaScript ?
The JavaScript fetch() method retrieves resources from a server and produces a Promise. We will see how to fetch XML data with JavaScript's Fetch API, parse responses into XML documents, and utilize DOM manipulation for streamlined data extraction with different methods. These are the following methods: Table of Content Using response.text() Method
3 min read
What are the disadvantages of using persistent connection in PDO ?
In PDO, a connection to the database can be persistent or non-persistent. Persistent connections make using the attribute PDO::ATTR_PERSISTENT. Persistent connections do not close when the script ends, but they are cached and can be reused when a requested persistent connection is identical to the existing connection. When a connection is requested
3 min read
What is the difference between MySQL, MySQLi and PDO?
To understand the difference between MySQL, MySQLi, and PDO, we must know about each one of them individually. These are nothing but the APIs of PHP that is used to access the MySQL databases and tables. The developers can choose either one of them for their project, however, it must be known that MySQL cannot be used with PHP 7 and its newer versi
6 min read