CRUD Operation using PHP/MySQLi with DataTable and TCPDF Tutorial

Language

This tutorial tackles how to a PHP Web Application with CRUD(create, read, update, and delete) operation using the two MySQLi Extensions which are OOP and Procedural. Also included, the data table library which is an extension that uses jquery to beautify and add functionality to HTML Table. PDF Generator using the TCPDF library is also included in this tutorial.

Getting Started

First of all, this tutorial requires the following software and plugins/liraries.

Before proceeding to the coding part, make sure that you have already started the "Apache" and "MySQL" server in your XAMPP's Control Panel.

Database Creation

  1. Open the PHPMyAdmin in a browser . i.e. http://localhost/phpmyadmin
  2. Create a new database naming mydatabase.
  3. Next, go to the SQL Tab of the PHPMyAdmin
  4. Copy the code SQL Code below and Paste it in the provided text box in the SQL Tab.
    1. CREATE TABLE `members` (
    2. `id` int(11) NOT NULL,
    3. `firstname` varchar(30) NOT NULL,
    4. `lastname` varchar(30) NOT NULL,
    5. `address` text NOT NULL
    6.  
    7. INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
    8. (1, 'neovic', 'devierte', 'silay city'),
    9. (2, 'gemalyn', 'cepe', 'carmen, bohol'),
    10. (3, 'lee', 'apilinga', 'bacolod'),
    11. (4, 'julyn', 'divinagracia', 'eb magalona'),
    12. (5, 'cristine', 'demapanag', 'talisay');
    13.  
    14. ALTER TABLE `members`
    15. ADD PRIMARY KEY (`id`);
    16. ALTER TABLE `members`

    You can also Import the provided SQL file that is included in the source code zip file.

Database Connection

Now, we will create new file naming connection.php. Copy and Paste the code below in you created file. Make sure to modify the database credentials according to your database setup.

  1. <?php
  2. //for MySQLi OOP
  3. $conn = new mysqli('localhost', 'root', '', 'mydatabase');
  4. if($conn->connect_error){
  5. die("Connection failed: " . $conn->connect_error);
  6. }
  7. ////////////////
  8.  
  9. //for MySQLi Procedural
  10. // $conn = mysqli_connect('localhost', 'root', '', 'mydatabase');
  11. // if(!$conn){
  12. // die("Connection failed: " . mysqli_connect_error());
  13. // }
  14. ////////////////
  15. ?>

Creating the Interface

Copy and Paste the below codes and save the files as the given file name above the scripts.

index.php
  1. <?php
  2. ?>
  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6. <meta charset="utf-8">
  7. <title>CRUD Operation using PHP/MySQLi with DataTable and PDF Generator using TCPDF</title>
  8. <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
  9. <link rel="stylesheet" type="text/css" href="datatable/dataTable.bootstrap.min.css">
  10. <style>
  11. .height10{
  12. height:10px;
  13. }
  14. .mtop10{
  15. margin-top:10px;
  16. }
  17. .modal-label{
  18. position:relative;
  19. top:7px
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <div class="container">
  25. <h1 class="page-header text-center">CRUD Operation with DataTable and PDF</h1>
  26. <div class="row">
  27. <div class="col-sm-8 col-sm-offset-2">
  28. <div class="row">
  29. <?php
  30. if(isset($_SESSION['error'])){
  31. echo
  32. "
  33. <div class='alert alert-danger text-center'>
  34. <button class='close'>&times;</button>
  35. ".$_SESSION['error']."
  36. </div>
  37. ";
  38. unset($_SESSION['error']);
  39. }
  40. if(isset($_SESSION['success'])){
  41. echo
  42. "
  43. <div class='alert alert-success text-center'>
  44. <button class='close'>&times;</button>
  45. ".$_SESSION['success']."
  46. </div>
  47. ";
  48. unset($_SESSION['success']);
  49. }
  50. ?>
  51. </div>
  52. <div class="row">
  53. <a href="#addnew" data-toggle="modal" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span> New</a>
  54. <a href="print_pdf.php" class="btn btn-success pull-right"><span class="glyphicon glyphicon-print"></span> PDF</a>
  55. </div>
  56. <div class="height10">
  57. </div>
  58. <div class="row">
  59. <table id="myTable" class="table table-bordered table-striped">
  60. <thead>
  61. <th>ID</th>
  62. <th>Firstname</th>
  63. <th>Lastname</th>
  64. <th>Address</th>
  65. <th>Action</th>
  66. </thead>
  67. <tbody>
  68. <?php
  69. include_once('connection.php');
  70. $sql = "SELECT * FROM members";
  71.  
  72. //use for MySQLi-OOP
  73. $query = $conn->query($sql);
  74. while($row = $query->fetch_assoc()){
  75. echo
  76. "<tr>
  77. <td>".$row['id']."</td>
  78. <td>".$row['firstname']."</td>
  79. <td>".$row['lastname']."</td>
  80. <td>".$row['address']."</td>
  81. <td>
  82. <a href='#edit_".$row['id']."' class='btn btn-success btn-sm' data-toggle='modal'><span class='glyphicon glyphicon-edit'></span> Edit</a>
  83. <a href='#delete_".$row['id']."' class='btn btn-danger btn-sm' data-toggle='modal'><span class='glyphicon glyphicon-trash'></span> Delete</a>
  84. </td>
  85. </tr>";
  86. include('edit_delete_modal.php');
  87. }
  88. /////////////////
  89.  
  90. //use for MySQLi Procedural
  91. // $query = mysqli_query($conn, $sql);
  92. // while($row = mysqli_fetch_assoc($query)){
  93. // echo
  94. // "<tr>
  95. // <td>".$row['id']."</td>
  96. // <td>".$row['firstname']."</td>
  97. // <td>".$row['lastname']."</td>
  98. // <td>".$row['address']."</td>
  99. // <td>
  100. // <a href='#edit_".$row['id']."' class='btn btn-success btn-sm' data-toggle='modal'><span class='glyphicon glyphicon-edit'></span> Edit</a>
  101. // <a href='#delete_".$row['id']."' class='btn btn-danger btn-sm' data-toggle='modal'><span class='glyphicon glyphicon-trash'></span> Delete</a>
  102. // </td>
  103. // </tr>";
  104. // include('edit_delete_modal.php');
  105. // }
  106. /////////////////
  107.  
  108. ?>
  109. </tbody>
  110. </table>
  111. </div>
  112. </div>
  113. </div>
  114. </div>
  115. <?php include('add_modal.php') ?>
  116.  
  117. <script src="jquery/jquery.min.js"></script>
  118. <script src="bootstrap/js/bootstrap.min.js"></script>
  119. <script src="datatable/jquery.dataTables.min.js"></script>
  120. <script src="datatable/dataTable.bootstrap.min.js"></script>
  121. <!-- generate datatable on our table -->
  122. <script>
  123. $(document).ready(function(){
  124. //inialize datatable
  125. $('#myTable').DataTable();
  126.  
  127. //hide alert
  128. $(document).on('click', '.close', function(){
  129. $('.alert').hide();
  130. })
  131. });
  132. </script>
  133. </body>
  134. </html>
add_modal.php
  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 modal-label">Firstname:</label>
  15. </div>
  16. <div class="col-sm-10">
  17. <input type="text" class="form-control" name="firstname" required>
  18. </div>
  19. </div>
  20. <div class="row form-group">
  21. <div class="col-sm-2">
  22. <label class="control-label modal-label">Lastname:</label>
  23. </div>
  24. <div class="col-sm-10">
  25. <input type="text" class="form-control" name="lastname" required>
  26. </div>
  27. </div>
  28. <div class="row form-group">
  29. <div class="col-sm-2">
  30. <label class="control-label modal-label">Address:</label>
  31. </div>
  32. <div class="col-sm-10">
  33. <input type="text" class="form-control" name="address" required>
  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>
edit_delete_modal.php
  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">
  12. <input type="hidden" class="form-control" name="id" value="<?php echo $row['id']; ?>">
  13. <div class="row form-group">
  14. <div class="col-sm-2">
  15. <label class="control-label modal-label">Firstname:</label>
  16. </div>
  17. <div class="col-sm-10">
  18. <input type="text" class="form-control" name="firstname" value="<?php echo $row['firstname']; ?>">
  19. </div>
  20. </div>
  21. <div class="row form-group">
  22. <div class="col-sm-2">
  23. <label class="control-label modal-label">Lastname:</label>
  24. </div>
  25. <div class="col-sm-10">
  26. <input type="text" class="form-control" name="lastname" value="<?php echo $row['lastname']; ?>">
  27. </div>
  28. </div>
  29. <div class="row form-group">
  30. <div class="col-sm-2">
  31. <label class="control-label modal-label">Address:</label>
  32. </div>
  33. <div class="col-sm-10">
  34. <input type="text" class="form-control" name="address" value="<?php echo $row['address']; ?>">
  35. </div>
  36. </div>
  37. </div>
  38. </div>
  39. <div class="modal-footer">
  40. <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
  41. <button type="submit" name="edit" class="btn btn-success"><span class="glyphicon glyphicon-check"></span> Update</a>
  42. </form>
  43. </div>
  44.  
  45. </div>
  46. </div>
  47. </div>
  48.  
  49. <!-- Delete -->
  50. <div class="modal fade" id="delete_<?php echo $row['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  51. <div class="modal-dialog">
  52. <div class="modal-content">
  53. <div class="modal-header">
  54. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  55. <center><h4 class="modal-title" id="myModalLabel">Delete Member</h4></center>
  56. </div>
  57. <div class="modal-body">
  58. <p class="text-center">Are you sure you want to Delete</p>
  59. <h2 class="text-center"><?php echo $row['firstname'].' '.$row['lastname']; ?></h2>
  60. </div>
  61. <div class="modal-footer">
  62. <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
  63. <a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Yes</a>
  64. </div>
  65.  
  66. </div>
  67. </div>
  68. </div>

Creating the Operations Scripts

Copy and paste the following codes and save the files as the file name above.

add.php
  1. <?php
  2. include_once('connection.php');
  3.  
  4. if(isset($_POST['add'])){
  5. $firstname = $_POST['firstname'];
  6. $lastname = $_POST['lastname'];
  7. $address = $_POST['address'];
  8. $sql = "INSERT INTO members (firstname, lastname, address) VALUES ('$firstname', '$lastname', '$address')";
  9.  
  10. //use for MySQLi OOP
  11. if($conn->query($sql)){
  12. $_SESSION['success'] = 'Member added successfully';
  13. }
  14. ///////////////
  15.  
  16. //use for MySQLi Procedural
  17. // if(mysqli_query($conn, $sql)){
  18. // $_SESSION['success'] = 'Member added successfully';
  19. // }
  20. //////////////
  21.  
  22. else{
  23. $_SESSION['error'] = 'Something went wrong while adding';
  24. }
  25. }
  26. else{
  27. $_SESSION['error'] = 'Fill up add form first';
  28. }
  29.  
  30. header('location: index.php');
  31. ?>
edit.php
  1. <?php
  2. include_once('connection.php');
  3.  
  4. if(isset($_POST['edit'])){
  5. $id = $_POST['id'];
  6. $firstname = $_POST['firstname'];
  7. $lastname = $_POST['lastname'];
  8. $address = $_POST['address'];
  9. $sql = "UPDATE members SET firstname = '$firstname', lastname = '$lastname', address = '$address' WHERE id = '$id'";
  10.  
  11. //use for MySQLi OOP
  12. if($conn->query($sql)){
  13. $_SESSION['success'] = 'Member updated successfully';
  14. }
  15. ///////////////
  16.  
  17. //use for MySQLi Procedural
  18. // if(mysqli_query($conn, $sql)){
  19. // $_SESSION['success'] = 'Member updated successfully';
  20. // }
  21. ///////////////
  22.  
  23. else{
  24. $_SESSION['error'] = 'Something went wrong in updating member';
  25. }
  26. }
  27. else{
  28. $_SESSION['error'] = 'Select member to edit first';
  29. }
  30.  
  31. header('location: index.php');
  32.  
  33. ?>
delete.php
  1. <?php
  2. include_once('connection.php');
  3.  
  4. if(isset($_GET['id'])){
  5. $sql = "DELETE FROM members WHERE id = '".$_GET['id']."'";
  6.  
  7. //use for MySQLi OOP
  8. if($conn->query($sql)){
  9. $_SESSION['success'] = 'Member deleted successfully';
  10. }
  11. ////////////////
  12.  
  13. //use for MySQLi Procedural
  14. // if(mysqli_query($conn, $sql)){
  15. // $_SESSION['success'] = 'Member deleted successfully';
  16. // }
  17. /////////////////
  18.  
  19. else{
  20. $_SESSION['error'] = 'Something went wrong in deleting member';
  21. }
  22. }
  23. else{
  24. $_SESSION['error'] = 'Select member to delete first';
  25. }
  26.  
  27. header('location: index.php');
  28. ?>

Generating PDF using TCPDF

Copy the code below and paste it into the blank file in your text editor and save it as print_pdf.php

  1. <?php
  2. function generateRow(){
  3. $contents = '';
  4. include_once('connection.php');
  5. $sql = "SELECT * FROM members";
  6.  
  7. //use for MySQLi OOP
  8. $query = $conn->query($sql);
  9. while($row = $query->fetch_assoc()){
  10. $contents .= "
  11. <tr>
  12. <td>".$row['id']."</td>
  13. <td>".$row['firstname']."</td>
  14. <td>".$row['lastname']."</td>
  15. <td>".$row['address']."</td>
  16. </tr>
  17. ";
  18. }
  19. ////////////////
  20.  
  21. //use for MySQLi Procedural
  22. // $query = mysqli_query($conn, $sql);
  23. // while($row = mysqli_fetch_assoc($query)){
  24. // $contents .= "
  25. // <tr>
  26. // <td>".$row['id']."</td>
  27. // <td>".$row['firstname']."</td>
  28. // <td>".$row['lastname']."</td>
  29. // <td>".$row['address']."</td>
  30. // </tr>
  31. // ";
  32. // }
  33. ////////////////
  34.  
  35. return $contents;
  36. }
  37.  
  38. require_once('tcpdf/tcpdf.php');
  39. $pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  40. $pdf->SetCreator(PDF_CREATOR);
  41. $pdf->SetTitle("Generated PDF using TCPDF");
  42. $pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);
  43. $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  44. $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
  45. $pdf->SetDefaultMonospacedFont('helvetica');
  46. $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
  47. $pdf->SetMargins(PDF_MARGIN_LEFT, '10', PDF_MARGIN_RIGHT);
  48. $pdf->setPrintHeader(false);
  49. $pdf->setPrintFooter(false);
  50. $pdf->SetAutoPageBreak(TRUE, 10);
  51. $pdf->SetFont('helvetica', '', 11);
  52. $pdf->AddPage();
  53. $content = '';
  54. $content .= '
  55. <h2 align="center">Generated PDF using TCPDF</h2>
  56. <h4>Members Table</h4>
  57. <table border="1" cellspacing="0" cellpadding="3">
  58. <tr>
  59. <th width="5%">ID</th>
  60. <th width="20%">Firstname</th>
  61. <th width="20%">Lastname</th>
  62. <th width="55%">Address</th>
  63. </tr>
  64. ';
  65. $content .= generateRow();
  66. $content .= '</table>';
  67. $pdf->writeHTML($content);
  68. $pdf->Output('members.pdf', 'I');
  69.  
  70.  
  71. ?>

Note: configure the require_once function path according to your TCTPDF Library path. In my case, it is compiled in a folder naming tcpdf

Demo

That's it. You are good to go. I hope this will help you for your future PHP Projects.

P.S. If you have any comments or suggestions on how to improve this, please don't hesitate to comment below or send me a message.

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

Submitted byAmlan (not verified)on Sat, 03/31/2018 - 01:57

Getting errors: Warning: mysqli::mysqli(): MySQL server has gone away in C:\wamp64\www\crud\connection.php on line 3 Warning: mysqli::mysqli(): Error while reading greeting packet. PID=9468 in C:\wamp64\www\crud\connection.php on line 3 Warning: mysqli::mysqli(): (HY000/2006): MySQL server has gone away in C:\wamp64\www\crud\connection.php on line 3 Solution plz!
Submitted bymichael86on Wed, 12/12/2018 - 11:24

Sir this is the best program for me, 1 thing you forgot, the image of employee, can you add with image of an employee? this is my email: [email protected] please sir I'm new tutorial oh html php. please i want to know how to upload image in your page. Thank you.
Submitted bywnc19on Sun, 08/21/2022 - 16:49

Thank this really works!.

If you won't mind bro, please show the tutorial on tcpdf on how to print to pdf the selected row or data from the database.

 

Thanks in advance bro

Submitted byGIASH (not verified)on Sun, 01/08/2023 - 15:24

Fatal error: Uncaught mysqli_sql_exception: Access denied for user 'root'@'localhost' (using password: NO) in C:\xampp\htdocs\demo\connection.php:3 Stack trace: #0 C:\xampp\htdocs\demo\connection.php(3): mysqli->__construct('localhost', 'root', Object(SensitiveParameterValue), 'mydatabase') #1 C:\xampp\htdocs\demo\index.php(70): include_once('C:\\xampp\\htdocs...') #2 {main} thrown in C:\xampp\htdocs\demo\connection.php on line 3

Add new comment