PHP OOP Insert Data Into Database
![]() |
Object Oriented PHP Insert Data Into Database |
Hi Guys in this lesson we are going to learn how to insert data into database in php oop concepts..
Please Follow the below instruction to insert data into database in php oop concepts
=>Database and Table:
Database Name: test
Table Name: user
User Below SQL Codes for Table
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;
=>Files : create to files named index.php and database.php
Codes for index .php
1. index.php
<?php include "database.php"; ?> <?php $db= new Database(); if(isset($_POST['submit'])){ $username=mysqli_real_escape_string($db->link,$_POST['username']); $email=mysqli_real_escape_string($db->link,$_POST['email']); if($username=='' || $email==''){ $error="Fields Must Not be empty"; }else{ $query="INSERT INTO user (username,email)VALUES('$username','$email')"; $create=$db->insert($query); } } ?> <form method="POST" action="create.php"> <table> <tr> <td>UserName:</td> <td><input type="text" name="username" placeholder="Your Username here"/></td> </tr> <tr> <td>Email:</td> <td><input type="text" name="email" placeholder="Your Email"/></td> </tr> <tr> <td></td> <td><input type="submit" name="submit" value="Insert Data"/> <input type="reset" value="Reset"/> </td> </tr> </table> </form> <?php if(isset($_GET['msg'])){ echo $_GET['msg']; } ?> <?php if(isset($error)){ echo $error; } ?>2. Database.php
<?php class Database{ public $host="localhost"; public $user="root"; public $pass=""; public $dbname="codenair"; 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; } } //Inserting Data Into Database public function insert($query){ $insert_row = $this->link->query($query) or die ($this->link->error.__LINE__); if($insert_row){ header("location:index.php?msg=".urlencode('Data Insert Successfull')); } } } ?>Practice This codes more and more to understand insert data into database in oop concepts.please leave your comment and keep visiting for more codes..Thank you...
No comments:
Post a Comment
Thank You for Your Comment
Note: Only a member of this blog may post a comment.