How to Fetch data from database Using OOPS In PHP
This post about how to fetch data from database using oops concept in PHP. In previous post i explained how to insert data using OOPs concepts. Now from the same table we will fetch the data.
1.Create a apge function.php inside this page define a class DB_con.
In DB_con class define a constructer for dbconnection and write a funtion for fetchdata.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php session_start(); define('DB_SERVER','localhost'); define('DB_USER','root'); define('DB_PASS' ,''); define('DB_NAME', 'demos'); class DB_con { function __construct() { $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME); $this->dbh=$con; // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } } public function fetchdata() { $result=mysqli_query($this->dbh,"select * from insertdata"); return $result; } } ?> |
2. create a page where you can create a object for class and call the fetchdata function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php include_once("function.php"); $fetchdata=new DB_con(); ?> <table width="100%" border="0" > <tr> <th width="9%" height="42" scope="col" >S no.</th> <th width="13%" scope="col">Name</th> <th width="11%" scope="col">Email</th> <th width="11%" scope="col">Contact no</th> <th width="11%" scope="col">Gender</th> <th width="13%" scope="col">Education</th> <th width="13%" scope="col">Address</th> <th width="19%" scope="col">PostingDate</th> </tr> <?php $sql=$fetchdata->fetchdata(); $cnt=1; while($row=mysqli_fetch_array($sql)) { ?> <tr> <td height="29"><?php echo $cnt;?></td> <td><?php echo $row['name'];?></td> <td><?php echo $row['email'];?></td> <td><?php echo $row['contactno'];?></td> <td><?php echo $row['gender'];?></td> <td><?php echo $row['education'];?></td> <td><?php echo $row['addrss'];?></td> <td><?php echo $row['posting_date'];?></td> </tr> <?php $cnt=$cnt+1;} ?> </table> |