PHP Data Insert using Dependency Injection

PHP Data Insert using OOP Dependency Injection

In this post, I will show you how to write OOP program with dependency injection in PHP to insert values into a database. First, we will create a table named ‘post’ into which we will be inserting the values. The table will have columns named id, title, description, and date. You can use the below sql script to create the table.

-- Table structure for table `post`

  `id` int(11) NOT NULL,
  `title` varchar(500) NOT NULL,
  `description` text NOT NULL,
  `date` date NOT NULL

-- Indexes for dumped tables

-- Indexes for table `post`

-- AUTO_INCREMENT for dumped tables

-- AUTO_INCREMENT for table `post`

Next, we can create a class in PHP to represent the post in a blog. We can create a method named insert() for inserting values into the table. I have created the below class to insert values into the table ‘post’.

class post {

    private $conn;

    //Use dependency injection to get the mysqli connection object.
    public function __construct(mysqli $conn) {
        $this->conn = $conn;

    public function insert($title, $description, $date) {
        $stmt = $this->conn->prepare('insert into post(title, description, date) values(?, ?, ?)');
        if (false === $stmt) {
            die('prepare() failed: ' . $this->conn->error);
        $rc = $stmt->bind_param('sss', $title, $description, $date);
        if (false === $rc) {
            die('bind_param() failed: ' . $stmt->error);


As you can see I have used dependency injection to get the connection object. So what is dependency injection?

Dependency Injection

Dependency injection is a technique in programming where one object supplies the dependencies of another object. As you can see in the example code above, the constructor has a parameter ‘$conn’ which is of type ‘mysqli class’. So while instantiating the class we can pass the connection object to the post object. The advantage is that we can pass the same connection object to different classes there by avoiding rewriting the same connection code in different classes. Dependency injection makes your code clean and readable. Advantages of dependency injection are it improves code reusability, helps in unit testing, reduce a components unnecessary dependency.

Next, we have to write the code for creating the form. What I will do is I will use the same page for creating the form and the code for processing the submitted form values. So I will submit the form to the same page.

require_once 'class.php'; 
if (isset($_POST['submit'])) 
{ $host = 'localhost'; 
$user = 'root'; 
$password = ''; 
$database = 'blog'; 
$title = $_POST['title']; 
$description = $_POST['description']; 
$date = $_POST['date']; 
if (empty($title) || empty($description) || empty($date)) 
die('Please enter all the values'); 
$conn = new mysqli($host, $user, $password, $database); 
if ($conn->connect_error) { 
die('Connect Error: ' . $conn->connect_error); 
$post = new post($conn); 
$post->insert($title, $description, $date); 
$_SESSION['msg'] = 'Successfully saved.'; 
header('Location: index.php'); 
} ?> 
<meta charset="UTF-8"> 
<!-- Latest compiled and minified CSS --> 
<link rel="stylesheet" href="" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> 
<link rel="stylesheet" href="" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> 
<!-- Latest compiled and minified JavaScript --> 
<script src="" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> 
<nav class="navbar navbar-inverse navbar-fixed-top"> 
<div class="container"> 
<div class="navbar-header"> 
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> 
<span class="sr-only">Toggle navigation</span> 
<span class="icon-bar"></span> 
<span class="icon-bar"></span> 
<span class="icon-bar"></span> 
<a class="navbar-brand" href="#"></a> </div> 
<div id="navbar" class="navbar-collapse collapse"> 
</div><!--/.navbar-collapse --> </div> 
<!-- Main jumbotron for a primary marketing message or call to action --> 
<div class="jumbotron"> 
<div class="container"> </div> </div> 
<div class="container"> 
<!-- Example row of columns -->
 <div class="row"> 
 <div class="col-md-4"> </div> 
 <div class="col-md-4"> 
 if (array_key_exists('msg', $_SESSION)) 
 if ($_SESSION['msg']) { ?> 
 <div class="alert alert-success"> 
 <strong><?php echo $_SESSION['msg']; ?></strong> </div> 
 <?php session_destroy(); } ?> 
 <form name="registration" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post"> 
 <h2 class="form-signin-heading">Post</h2> 
 <div class="row"> 
 <div class="col-lg-12"> 
 <input type="text" name="title" placeholder="Title" class="form-control" required autofocus> </div> 
 </div> <div class="row"> <div class="col-lg-12"> 
 <input type="date" name="date" placeholder="Date" class="form-control" required autofocus> </div> 
 </div> <div class="row"> <div class="col-lg-12"> 
 <textarea name="description" placeholder="Description" class="form-control" required></textarea> 
 <div class="row"> 
 <div class="col-lg-12"> 
 <input type="submit" name="submit" value="Submit" class="btn btn-lg btn-primary btn-block"> 
 <div class="col-md-4"> 
 <!-- /container --> 

After the form is submitted the PHP code will create a new connection object and will create the post object by passing the connection objection to it. So this is a simple example of writing object oriented code in php to insert values into a table. If you have any questions please comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *