August 1, 2016
Insert data into Mysql Database using OOPS in PHP

Hi, friends in this tutorial I show you how to Insert a data in MySQL using PHP OOPS(Object Oriented Programming). In PHP if you are using OOPS then it will become very easy to insert data into the MySQL table. In this tutorial, you can see I have made one PHP class for Inserting data into MySQL table. In this, I used __construct() megic methods of PHP for creating DB(database) connection. In this PHP megic method when a new object of the class will be generated then whenever code runs below this method.
index.php
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<?php //Include Database include 'db.php'; $data = new Databases; $msg = ''; if(isset($_POST["submit"])) { $insert_data = array( 'name' => mysqli_real_escape_string($data->con, $_POST['name']), 'age' => mysqli_real_escape_string($data->con, $_POST['age']), ); if($data->insert('emp_info', $insert_data)) { $msg = "Inserted Data Successfully!"; } } ?> <!doctype html> <html> <head> <title>Insert data into Mysql Database using OOPS in PHP | SoftAOX</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> </head> <body> <h1>Insert data into Mysql Database using OOPS in PHP | SoftAOX</h1> <form method="post"> <label>Name</label> <input type="text" name="name"> <br /> <br /> <label>Age</label> <input type="text" name="age"> <br /> <br /> <input type="submit" name="submit" value="Submit"> <span> <?php if(isset($msg)) { echo $msg; } ?> </span> </form> </body> </html> |
db.php
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 |
<?php //Database class Databases{ public $con; public $error; public function __construct() { $this->con = mysqli_connect("localhost", "root", "", "tut"); if(!$this->con) { echo 'Database Connection Error' . mysqli_connect_error($this->con); } } public function insert($table_name, $data) { $string = "INSERT INTO ".$table_name." ("; $string .= implode(",", array_keys($data)) . ') VALUES ('; $string .= "'" . implode("','", array_values($data)) . "')"; if(mysqli_query($this->con, $string)) { return true; } else { echo mysqli_error($this->con); } } } ?> |
Download
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]