PHP script to retrieve and display all records of table student details

In this tutorial, how to create a PHP script to retrieve or fetch and display all records of table student details using MySQL database is simple to do with the following attributes.

And using MySQL select query in PHP to fetch data and display it in the front end.

In the database table create 3 columns and name with student_name, class, mobile no




create table student_details
(
student_id int AUTO_INCREMENT PRIMARY KEY,
student_name varchar(50) not null,
class varchar(30) not null,
mobileno varchar(50) not null
);


Insert values into Database:



INSERT INTO student_details(student_name,class,mobileno) 
VALUES ('chandra',9,9874563211);
INSERT INTO student_details(student_name,class,mobileno) 
VALUES ('anbu',8,9874563213);
INSERT INTO student_details(student_name,class,mobileno) 
VALUES ('priya',9,9874563214);
INSERT INTO student_details(student_name,class,mobileno) 
VALUES ('vidya',9,9874563215);
INSERT INTO student_details(student_name,class,mobileno) 
VALUES ('manikadan',8,9874563217);




Here, I created a php file named fetch.php with where the following steps below:



Connect to database(dbcon.php):



<?php
$servername = "localhost";
$username = "root";
$password = "";

try {
  $conn = new PDO("mysql:host=$servername;dbname=phptut", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  //echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
?>


fetch.php



<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>php fetch</title>
</head>
  <body>
    <h1>PHP FETCH DATA</h1>
   <div class="container">
 <?php require_once 'dbcon.php';?>
  <?php
      $sql = "SELECT * FROM student_details";
      $result = $conn->query($sql);
      echo '<table class="table table-bordered">';
      echo '<th>student_id</th>';
      echo '<th>student_name</th>';
      echo '<th>class</th>';
      echo '<th>Mobile No</th>';
      while($row= $result ->fetch()){
       echo '<tr>';
       echo '<td>'.$row[0].'</td>';
       echo '<td>'.$row[1].'</td>';
       echo '<td>'.$row[2].'</td>';
       echo '<td>'.$row[3].'</td>';
       echo '</tr>';
       
      } 
      echo '</table>';
   ?>
</div>
  </body>
</html>


Output:


retrieve and display all records using php

Post a Comment

Previous Post Next Post