How to Insert Data in PHP OOP using MySqli Object Oriented

PHP OOPS - Insert data in database in php oop with MySqli Object Oriented.


In this post, you will be learning about how to insert data into database in php mysql using oops concept. So, we will be using bootstrap 5 for designing the html form user interface.

We are going to MySqli Object Oriented to insert data in php oop.

Step 1: Create a table into your database as follows:

CREATE TABLE IF NOT EXISTS `students` (
    `id` int(11) NOT NULL,
    `fullname` varchar(191) NOT NULL,
    `email` varchar(191) NOT NULL,
    `phone` varchar(20) NOT NULL,
    `course` varchar(20) NOT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;


Step 2: Create a student-add.php file and paste the below html form designed using bootstrap.

<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP OOPS - Insert Data into database in php mysql using oops</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>
   
    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
                <?php
                    if(isset($_SESSION['message']))
                    {
                        echo "<h5>".$_SESSION['message']."</h5>";
                        unset($_SESSION['message']);
                    }
                ?>
                <div class="card">
                    <div class="card-header">
                        <h4>Student Add</h4>
                    </div>
                    <div class="card-body">

                        <form action="code.php" method="POST">
                            <div class="mb-3">
                                <label for="">Full Name</label>
                                <input type="text" name="fullname" required class="form-control" />
                            </div>
                            <div class="mb-3">
                                <label for="">Email ID</label>
                                <input type="text" name="email" required class="form-control" />
                            </div>
                            <div class="mb-3">
                                <label for="">Course</label>
                                <input type="text" name="course" required class="form-control" />
                            </div>
                            <div class="mb-3">
                                <label for="">Phone No</label>
                                <input type="text" name="phone" required class="form-control" />
                            </div>
                            <div class="mb-3">
                                <button type="submit" name="save_student" class="btn btn-primary">Save Student</button>
                            </div>
                        </form>

                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>


Step 3: Create a database connection. create a file dbconn.php and paste the below code:

Example: Database Connection with MySqli Object Oriented.

<?php

define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_DATABASE','adminpanel');

class DatabaseConnection
{
    public function __construct()
    {
        $conn = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);

        if($conn->connect_error)
        {
            die ("<h1>Database Connection Failed</h1>");
        }
        //echo "Database Connected Successfully";
        return $this->conn = $conn;
    }
}

?>


Step 4: Create a code.php file and paste the below:

In this file, we will include the database connection file and StudentController.php file.

<?php
session_start();

include('dbconn.php');
include('StudentController.php');

$db = new DatabaseConnection;

if(isset($_POST['save_student']))
{
    $inputData = [
        'fullname' => mysqli_real_escape_string($db->conn,$_POST['fullname']),
        'email' => mysqli_real_escape_string($db->conn,$_POST['email']),
        'phone' => mysqli_real_escape_string($db->conn,$_POST['phone']),
        'course' => mysqli_real_escape_string($db->conn,$_POST['course']),
    ];

    $student = new StudentController;
    $result = $student->create($inputData);
   
    if($result)
{
$_SESSION['message'] = "Student Added Successfully";
    header("Location: student-add.php");
    exit(0);
    }
else
{
  $_SESSION['message'] = "Not Inserted";
    header("Location: student-add.php");
    exit(0);
    }
}
?>


Step 5: Create a StudentController.php file and paste the below to insert data into database.

Example: Insert Query with MySqli Object Oriented.

<?php

class StudentController
{
    public function __construct()
    {
        $db = new DatabaseConnection;
        $this->conn = $db->conn;
    }

    public function create($inputData)
    {
        $fullname = $inputData['fullname'];
        $email = $inputData['email'];
        $phone = $inputData['phone'];
        $course = $inputData['course'];

        $studentQuery = "INSERT INTO students (fullname,email,phone,course) VALUES ('$fullname','$email','$phone','$course')";
        $result = $this->conn->query($studentQuery);
        if($result){
            return true;
        }else{
            return false;
        }
    }
}
?>


Thank you.

© Copyright - 2018 - 2022 | All rights reserved at Funda of Web IT