• Thu, Nov 2024

How to fetch data from PostgreSQL using PHP

How to fetch data from PostgreSQL using PHP

We learned how to use PHP to insert data into PostgreSQL in the last tutorial. This article will teach you how to use PHP to get and read data that has been inserted into PostgreSQL.

config.php: This is used to connect PHP to PostgreSQL databases.

read.php: This is where HTML tables are utilized, and we'll also place the PHP code for data fetch and read here.

The PostgreSQL database and table from the last tutorial will be used.

Workers' structure


PHP code to retrieve data from PostgreSQL

<table class="table table-striped">
               <thead>
                   <tr>
                       <th>#</th>
                       <th>Name</th>
                       <th>Email Id</th>
                       <th>Mobile No</th>
                       <th>Department</th>
                       <th>Creation Date</th>
                   </tr>
               </thead>
               <tbody>
<?php $query= pg_query($conn,"select * from employee");
$cnt=1;
while($row=pg_fetch_array($query)){
?>
                   <tr>
                       <td><?php echo $cnt;?></td>
                       <td><?php echo $row['name'];?></td>
                       <td><?php echo $row['emailid'];?></td>
                       <td><?php echo $row['mobileno'];?></td>
                       <td><?php echo $row['department'];?></td>
                       <td><?php echo $row['creationdate'];?></td>
                   </tr>
               <?php $cnt++;} ?>
                    
               </tbody>
           </table>