Fetch data from database in php oop
![]() |
Fetch data from database in php oop |
Hi Guys in this lesson we are going to learn how fetch data from database in php oop concepts.
follow the below examples to learn fetch data in php oop concepts
Database Name: test
Table Name: user
SQL Codes for Table user
CREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(150) NOT NULL, `email` varchar(150) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;Insert rows into user use the below sql codes..
INSERT INTO `user` (`id`, `username`, `email`) VALUES (NULL, 'ANJAN KUMAR', 'Anjankumardhali@gmail.com'), (NULL, 'ANJAN', 'biswasshiuli608@gmail.com'), (NULL, 'Supriya Gain', 'SupriyaStar@Yahoo.com'), (NULL, 'ANJAN KUMAR', 'Anjankumardhali@gmail.com'), (NULL, 'ANJAN', 'biswasshiuli608@gmail.com'), (NULL, 'ANJANBD', 'biswasshiuli608@gmail.com');
Create 2 files named index.php and database.php
Database.php file contain our fetch class and database configuration.
1. index.php
<?php include('database.php'); $obj=new Database(); $query="SELECT*FROM user"; $result=$obj->fetch($query); ?> <h2>Fetch Data From database in PHP OOP</h2> <table border="1" cellspacing="0" cellpadding="2"> <tr> <th>ID</th> <th>UserName</th> <th>Email</th> </tr> <?php if($result){ while($row=$result->fetch_assoc()){?> <tr> <td><?php echo $row['id'];?></td> <td><?php echo $row['username'];?></td> <td><?php echo $row['email'];?></td> </tr> <?php }}else{ echo "No Result Found in Your Database"; } ?> </table>
2. database.php
<?php class Database{ public $host="localhost"; public $user="root"; public $pass=""; public $dbname="test"; public $link; public $error; public function __construct(){ $this->connectDB(); } //Connecting Database private function connectDB(){ $this->link = new mysqli($this->host,$this->user,$this->pass,$this->dbname); if(!$this->link){ $this->error= "Connection Failed".$this->link->connect_error; return false; } } //Fetching Data public function fetch($query){ $result= $this->link->query($query) or die ($this->link->error.__LINE__); if($result->num_rows>0){ return $result; }else{ return false; } } } ?>Practice This codes to understand How to fetch data from database in php oop concepts..Keep Visiting for more codes and leave your comment.Thank you..
No comments:
Post a Comment
Thank You for Your Comment
Note: Only a member of this blog may post a comment.