PHP CRUD Operation using PDO with Bootstrap/Modal Tutorial

Language

This tutorial tackles on how to CRUD(create, read, update, delete) MySQL database using PDO with Bootstrap/Modal. PDO as per the PHP manual stands for PHP Data Objects, a lightweight, consistent interface for accessing databases in PHP. We use Bootstrap/Modal in this tutorial to handle our forms.

Getting Started

I've used bootstrap and jQuery in this tutorial to enable bootstrap modals. These files are included in the downloadable of this tutorial but, if you want, you may download them using the links below:

Bootstrap jQuery

Creating our Database

Next, we create our MySQL database.

I've included a .sql file in the downloadable of this tutorial which is a mysql database file. All you have to do is import the said file. If you have no idea on how to do this, please refer to my tutorial, How import .sql file to restore MySQL database.

You should be able to create a database with tables named mydatabase.

Creating our Connection

Next, we create a connection to our database by creating a new file, name it as connection.php and paste the codes below.

  1. <?php
  2.  
  3. Class Connection{
  4.  
  5.         private $server = "mysql:host=localhost;dbname=mydatabase";
  6.         private $username = "root";
  7.         private $password = "";
  8.         private $options  = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,);
  9.         protected $conn;
  10.        
  11.         public function open(){
  12.                 try{
  13.                         $this->conn = new PDO($this->server, $this->username, $this->password, $this->options);
  14.                         return $this->conn;
  15.                 }
  16.                 catch (PDOException $e){
  17.                         echo "There is some problem in connection: " . $e->getMessage();
  18.                 }
  19.  
  20.     }
  21.  
  22.         public function close(){
  23.                 $this->conn = null;
  24.         }
  25.  
  26. }
  27.  
  28. ?>

In here, we have created a class named Connection and we are going to include this file and create a new object for our connection if we want to connect to our database.

Displaying our Data

Next, we are going to display that data in our table by creating a new file, name it as our index.php and paste the below codes.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.         <meta charset="utf-8">
  5.         <title>PHP CRUD Operation using PDO with Bootstrap/Modal</title>
  6.         <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
  7. </head>
  8. <body>
  9. <div class="container">
  10.         <h1 class="page-header text-center">PHP CRUD Operation using PDO</h1>
  11.         <div class="row">
  12.                 <div class="col-sm-8 col-sm-offset-2">
  13.                         <a href="#addnew" class="btn btn-primary" data-toggle="modal"><span class="glyphicon glyphicon-plus"></span> New</a>
  14.             <?php
  15.                 session_start();
  16.                 if(isset($_SESSION['message'])){
  17.                     ?>
  18.                     <div class="alert alert-info text-center" style="margin-top:20px;">
  19.                         <?php echo $_SESSION['message']; ?>
  20.                     </div>
  21.                     <?php
  22.  
  23.                     unset($_SESSION['message']);
  24.                 }
  25.             ?>
  26.                         <table class="table table-bordered table-striped" style="margin-top:20px;">
  27.                                 <thead>
  28.                                         <th>ID</th>
  29.                                         <th>Firstname</th>
  30.                                         <th>Lastname</th>
  31.                                         <th>Address</th>
  32.                                         <th>Action</th>
  33.                                 </thead>
  34.                                 <tbody>
  35.                                         <?php
  36.                                                 //include our connection
  37.                                                 include_once('connection.php');
  38.  
  39.                                                 $database = new Connection();
  40.                                         $db = $database->open();
  41.                                                 try{   
  42.                                                     $sql = 'SELECT * FROM members';
  43.                                                     foreach ($db->query($sql) as $row) {
  44.                                                         ?>
  45.                                                         <tr>
  46.                                                                 <td><?php echo $row['id']; ?></td>
  47.                                                                 <td><?php echo $row['firstname']; ?></td>
  48.                                                                 <td><?php echo $row['lastname']; ?></td>
  49.                                                                 <td><?php echo $row['address']; ?></td>
  50.                                                                 <td>
  51.                                                                         <a href="#edit_<?php echo $row['id']; ?>" class="btn btn-success btn-sm" data-toggle="modal"><span class="glyphicon glyphicon-edit"></span> Edit</a>
  52.                                                                         <a href="#delete_<?php echo $row['id']; ?>" class="btn btn-danger btn-sm" data-toggle="modal"><span class="glyphicon glyphicon-trash"></span> Delete</a>
  53.                                                                 </td>
  54.                                                                 <?php include('edit_delete_modal.php'); ?>
  55.                                                         </tr>
  56.                                                         <?php
  57.                                                     }
  58.                                                 }
  59.                                                 catch(PDOException $e){
  60.                                                         echo "There is some problem in connection: " . $e->getMessage();
  61.                                                 }
  62.  
  63.                                                 //close connection
  64.                                                 $database->close();
  65.  
  66.                                         ?>
  67.                                 </tbody>
  68.                         </table>
  69.                 </div>
  70.         </div>
  71. </div>
  72. <?php include('add_modal.php'); ?>
  73. <script src="jquery.min.js"></script>
  74. <script src="bootstrap/js/bootstrap.min.js"></script>
  75. </body>
  76. </html>

Creating our Add Modal

Next, we create the modal that will hold our add form by creating a new file, name it as add_modal.php and paste the below codes.

  1. <!-- Add New -->
  2. <div class="modal fade" id="addnew" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  3.     <div class="modal-dialog">
  4.         <div class="modal-content">
  5.             <div class="modal-header">
  6.                 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  7.                 <center><h4 class="modal-title" id="myModalLabel">Add New</h4></center>
  8.             </div>
  9.             <div class="modal-body">
  10.                         <div class="container-fluid">
  11.                         <form method="POST" action="add.php">
  12.                                 <div class="row form-group">
  13.                                         <div class="col-sm-2">
  14.                                                 <label class="control-label" style="position:relative; top:7px;">Firstname:</label>
  15.                                         </div>
  16.                                         <div class="col-sm-10">
  17.                                                 <input type="text" class="form-control" name="firstname">
  18.                                         </div>
  19.                                 </div>
  20.                                 <div class="row form-group">
  21.                                         <div class="col-sm-2">
  22.                                                 <label class="control-label" style="position:relative; top:7px;">Lastname:</label>
  23.                                         </div>
  24.                                         <div class="col-sm-10">
  25.                                                 <input type="text" class="form-control" name="lastname">
  26.                                         </div>
  27.                                 </div>
  28.                                 <div class="row form-group">
  29.                                         <div class="col-sm-2">
  30.                                                 <label class="control-label" style="position:relative; top:7px;">Address:</label>
  31.                                         </div>
  32.                                         <div class="col-sm-10">
  33.                                                 <input type="text" class="form-control" name="address">
  34.                                         </div>
  35.                                 </div>
  36.             </div>
  37.                         </div>
  38.             <div class="modal-footer">
  39.                 <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
  40.                 <button type="submit" name="add" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</a>
  41.                         </form>
  42.             </div>
  43.  
  44.         </div>
  45.     </div>
  46. </div>

Creating our Edit and Delete Modal

Next, we create the modal for our edit and delete. Create a new file, name it as edit_delete_modal.php and paste the below codes.

  1. <!-- Edit -->
  2. <div class="modal fade" id="edit_<?php echo $row['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  3.     <div class="modal-dialog">
  4.         <div class="modal-content">
  5.             <div class="modal-header">
  6.                 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  7.                 <center><h4 class="modal-title" id="myModalLabel">Edit Member</h4></center>
  8.             </div>
  9.             <div class="modal-body">
  10.                         <div class="container-fluid">
  11.                         <form method="POST" action="edit.php?id=<?php echo $row['id']; ?>">
  12.                                 <div class="row form-group">
  13.                                         <div class="col-sm-2">
  14.                                                 <label class="control-label" style="position:relative; top:7px;">Firstname:</label>
  15.                                         </div>
  16.                                         <div class="col-sm-10">
  17.                                                 <input type="text" class="form-control" name="firstname" value="<?php echo $row['firstname']; ?>">
  18.                                         </div>
  19.                                 </div>
  20.                                 <div class="row form-group">
  21.                                         <div class="col-sm-2">
  22.                                                 <label class="control-label" style="position:relative; top:7px;">Lastname:</label>
  23.                                         </div>
  24.                                         <div class="col-sm-10">
  25.                                                 <input type="text" class="form-control" name="lastname" value="<?php echo $row['lastname']; ?>">
  26.                                         </div>
  27.                                 </div>
  28.                                 <div class="row form-group">
  29.                                         <div class="col-sm-2">
  30.                                                 <label class="control-label" style="position:relative; top:7px;">Address:</label>
  31.                                         </div>
  32.                                         <div class="col-sm-10">
  33.                                                 <input type="text" class="form-control" name="address" value="<?php echo $row['address']; ?>">
  34.                                         </div>
  35.                                 </div>
  36.             </div>
  37.                         </div>
  38.             <div class="modal-footer">
  39.                 <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
  40.                 <button type="submit" name="edit" class="btn btn-success"><span class="glyphicon glyphicon-check"></span> Update</a>
  41.                         </form>
  42.             </div>
  43.  
  44.         </div>
  45.     </div>
  46. </div>
  47.  
  48. <!-- Delete -->
  49. <div class="modal fade" id="delete_<?php echo $row['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  50.     <div class="modal-dialog">
  51.         <div class="modal-content">
  52.             <div class="modal-header">
  53.                 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  54.                 <center><h4 class="modal-title" id="myModalLabel">Delete Member</h4></center>
  55.             </div>
  56.             <div class="modal-body">   
  57.                 <p class="text-center">Are you sure you want to Delete</p>
  58.                                 <h2 class="text-center"><?php echo $row['firstname'].' '.$row['lastname']; ?></h2>
  59.                         </div>
  60.             <div class="modal-footer">
  61.                 <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
  62.                 <a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Yes</a>
  63.             </div>
  64.  
  65.         </div>
  66.     </div>
  67. </div>

Creating our Add Script

Next, we create our script that will add data to our database. Create a new file, name it as add.php and paste the code below.

  1. <?php
  2.         session_start();
  3.         include_once('connection.php');
  4.  
  5.         if(isset($_POST['add'])){
  6.                 $database = new Connection();
  7.                 $db = $database->open();
  8.                 try{
  9.                         //make use of prepared statement to prevent sql injection
  10.                         $stmt = $db->prepare("INSERT INTO members (firstname, lastname, address) VALUES (:firstname, :lastname, :address)");
  11.                         //if-else statement in executing our prepared statement
  12.                         $_SESSION['message'] = ( $stmt->execute(array(':firstname' => $_POST['firstname'] , ':lastname' => $_POST['lastname'] , ':address' => $_POST['address'])) ) ? 'Member added successfully' : 'Something went wrong. Cannot add member'; 
  13.            
  14.                 }
  15.                 catch(PDOException $e){
  16.                         $_SESSION['message'] = $e->getMessage();
  17.                 }
  18.  
  19.                 //close connection
  20.                 $database->close();
  21.         }
  22.  
  23.         else{
  24.                 $_SESSION['message'] = 'Fill up add form first';
  25.         }
  26.  
  27.         header('location: index.php');
  28.        
  29. ?>

Creating our Edit Script

Next, we create our edit script by creating a new file, name it as edit.php and paste the below codes.

  1. <?php
  2.         session_start();
  3.         include_once('connection.php');
  4.  
  5.         if(isset($_POST['edit'])){
  6.                 $database = new Connection();
  7.                 $db = $database->open();
  8.                 try{
  9.                         $id = $_GET['id'];
  10.                         $firstname = $_POST['firstname'];
  11.                         $lastname = $_POST['lastname'];
  12.                         $address = $_POST['address'];
  13.  
  14.                         $sql = "UPDATE members SET firstname = '$firstname', lastname = '$lastname', address = '$address' WHERE id = '$id'";
  15.                         //if-else statement in executing our query
  16.                         $_SESSION['message'] = ( $db->exec($sql) ) ? 'Member updated successfully' : 'Something went wrong. Cannot update member';
  17.  
  18.                 }
  19.                 catch(PDOException $e){
  20.                         $_SESSION['message'] = $e->getMessage();
  21.                 }
  22.  
  23.                 //close connection
  24.                 $database->close();
  25.         }
  26.         else{
  27.                 $_SESSION['message'] = 'Fill up edit form first';
  28.         }
  29.  
  30.         header('location: index.php');
  31.  
  32. ?>

Creating our Delete Script

Lastly, we create our delete script which will delete our selected row by creating a new file, name it as delete.php and paste the below codes.

  1. <?php
  2.         session_start();
  3.         include_once('connection.php');
  4.  
  5.         if(isset($_GET['id'])){
  6.                 $database = new Connection();
  7.                 $db = $database->open();
  8.                 try{
  9.                         $sql = "DELETE FROM members WHERE id = '".$_GET['id']."'";
  10.                         //if-else statement in executing our query
  11.                         $_SESSION['message'] = ( $db->exec($sql) ) ? 'Member deleted successfully' : 'Something went wrong. Cannot delete member';
  12.                 }
  13.                 catch(PDOException $e){
  14.                         $_SESSION['message'] = $e->getMessage();
  15.                 }
  16.  
  17.                 //close connection
  18.                 $database->close();
  19.  
  20.         }
  21.         else{
  22.                 $_SESSION['message'] = 'Select member to delete first';
  23.         }
  24.  
  25.         header('location: index.php');
  26.  
  27. ?>
DEMO

That ends this tutorial. I hope this will help you and you have learn something usefull with this tutorial. You can download my sample source code that I have created for this tutorial by clicking the Download button below. Explore more in this website for more tutorials and Free project source codes.

Happy Coding :)

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

Hello, first of all, great tutorial! I want to use the Modal CRUD for my website, but I have MSSQL Server, not MYSQL, but this should not be a problem. I have made a Modal with taps, in the first tab there will be shown general information, in the second one there will be a kind of chat. I can open the modal, can select the tabs, I can see the right entries but I have a problem to add a new chat entry. This is my add.php:
  1. include_once 'dbconfig.php';
  2.          $message      = $_POST['message'];
  3.          $regid       = $_POST["reqid"];
  4.          try
  5.                 {
  6.                         $stmt =$DB_con -> prepare("INSERT INTO dbo.RequestChat (ReqID, message) VALUES (:id, :message)");
  7.                                
  8.         $stmt->bindParam(':id',$regid);
  9.         $stmt->bindParam(':message',$message);
  10.         $stmt->execute();
  11.                         return true;
  12.                 }
  13.                 catch(PDOException $e)
  14.                 {
  15.                         echo $e->getMessage(); 
  16.                         return false;
  17.                 }
  18.                
I have added this code to my index.php to test the add function, it works, it seems that there is something missing in the modal or in the add.php, so the values can nit been written in the database. Do you have an idea why I can not add something in the database. BR Sven

Hi there, first of all, great Tutorial, I want to use CRUD with Modal in my website, but I have a problem to add new entries in my database. I am using MSSQL, here is my add.php:
  1. include_once 'dbconfig.php';
  2.           $message      = $_POST['message'];
  3.           $regid       = $_POST["reqid"];
  4.    
  5.   try
  6.                 {
  7.                         $stmt =$DB_con -> prepare("INSERT INTO dbo.RequestChat (ReqID, message) VALUES (:id, :message)");
  8.                                
  9.         $stmt->bindParam(':id',$regid);
  10.         $stmt->bindParam(':message',$message);
  11.         $stmt->execute();
  12.        
  13.                         return true;
  14.                 }
  15.                 catch(PDOException $e)
  16.                 {
  17.                         echo $e->getMessage(); 
  18.                         return false;
  19.                 }      
I have tested this code in my index.php, it works like a charm. but when I use it like in your Tutorial, I can not add a new entry in the database. Do you have an idea where my failure is? BR Sven

Hi there, firat of all, very coot tutorial! I want to use CRUD with Modal and MSSQL, but I have a problem by adding a new entry in MSSQL Database, my add.php loosk like:
  1. include_once 'dbconfig.php';
  2.          $message      = $_POST['message'];
  3.          $regid       = $_POST["reqid"];
  4.   try
  5.                 {
  6.                         $stmt =$DB_con -> prepare("INSERT INTO dbo.RequestChat (ReqID, message) VALUES (:id, :message)");
  7.         $stmt->bindParam(':id',$regid);
  8.         $stmt->bindParam(':message',$message);
  9.         $stmt->execute();
  10.                         return true;
  11.                 }
  12.                 catch(PDOException $e)
  13.                 {
  14.                         echo $e->getMessage(); 
  15.                         return false;
  16. }
Do you have am idea why i can not add something in the database? BR Sven

Thank you for sharing your efforts by this project. it realy helps

Thanks for the contribution ... how can I add a paging??

This project is great but it lacks mobile support. Mobile browser still display desktop sizes. Can we add mobile sizes?

Add new comment