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

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

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

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

2. Create Table: Create table “studentRecord”, inside “fetch” database.

3. Create Table Structure: Table “studentRecord” containing 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).

The structure of table will look like this

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

Or you can write sql query to insert the values.

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

5. Create a folder “fetch”, that includes these two following files: The folder should be in “D:\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 studentrecord;

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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 studentrecord");
                           $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>

chevron_right


5.2. connection.php:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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 Database in PHP PDO.

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.