PHP PDO CRUD Tutorial using OOP with Bootstrap | Coding Cage

PHP PDO CRUD Tutorial using OOP with Bootstrap

By
In this tutorial we will see that how to create database CRUD operations using Object Oriented concept in PDO with Bootstrap framework, i have used here Bootstrap framework for front-end design and the MySQL database operations will done by PDO and OOP, recently i have posted pagination tutorial using PDO and OOP and one of my blog reader request me to post that how to use OOP concept to create CRUD operations in PDO, so in this tutorial i I'm going to explain OOP with PDO using Bootstrap framework. so Learn PHP OOP with PDO.
PHP PDO CRUD tutorial using OOP with Bootstrap
 

Database Design & table

create database named 'dbpdo' and import the following code in your phpmyadmin it will create table and user fields.

CREATE TABLE IF NOT EXISTS `tbl_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(25) NOT NULL,
  `last_name` varchar(25) NOT NULL,
  `email_id` varchar(50) NOT NULL,
  `contact_no` bigint(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;

Directory

our directory will be as follow :

bootstrap/
├── css/
│   ├── bootstrap.min.css
├── js/
│   └── bootstrap.min.js
└── fonts/
    ├── glyphicons-halflings-regular.eot
    ├── glyphicons-halflings-regular.svg
    ├── glyphicons-halflings-regular.ttf
    └── glyphicons-halflings-regular.woff
add-data.php
class.crud.php
dbconfig.php
delete.php
edit-data.php
footer.php
header.php
index.php

dbconfig.php

Set the credentials for the database and make a new PDO connection if the connection fails display the error . Next include the ‘class.crud.php’ file and make an instance of it, pass in the database object to the class to make use of the database.

<?php

$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "dbpdo";


try
{
 $DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
 $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
 echo $e->getMessage();
}

include_once 'class.crud.php';

$crud = new crud($DB_con);

?>

class.crud.php

this is the main class file which contains code for database operations.
create() and update() functions are in try/catch block to handle exceptions.
dataview() function selects the whole records from database table.
paging() function set’s the QueryString like “page_no=number”.
paginglink() function creates the paging number links with “previoue and next” feature.
all the CRUD and Pagination operations are done by this file.
<?php

class crud
{
 private $db;
 
 function __construct($DB_con)
 {
  $this->db = $DB_con;
 }
 
 public function create($fname,$lname,$email,$contact)
 {
  try
  {
   $stmt = $this->db->prepare("INSERT INTO tbl_users(first_name,last_name,email_id,contact_no) VALUES(:fname, :lname, :email, :contact)");
   $stmt->bindparam(":fname",$fname);
   $stmt->bindparam(":lname",$lname);
   $stmt->bindparam(":email",$email);
   $stmt->bindparam(":contact",$contact);
   $stmt->execute();
   return true;
  }
  catch(PDOException $e)
  {
   echo $e->getMessage(); 
   return false;
  }
  
 }
 
 public function getID($id)
 {
  $stmt = $this->db->prepare("SELECT * FROM tbl_users WHERE id=:id");
  $stmt->execute(array(":id"=>$id));
  $editRow=$stmt->fetch(PDO::FETCH_ASSOC);
  return $editRow;
 }
 
 public function update($id,$fname,$lname,$email,$contact)
 {
  try
  {
   $stmt=$this->db->prepare("UPDATE tbl_users SET first_name=:fname, 
                                                 last_name=:lname, 
                email_id=:email, 
                contact_no=:contact
             WHERE id=:id ");
   $stmt->bindparam(":fname",$fname);
   $stmt->bindparam(":lname",$lname);
   $stmt->bindparam(":email",$email);
   $stmt->bindparam(":contact",$contact);
   $stmt->bindparam(":id",$id);
   $stmt->execute();
   
   return true; 
  }
  catch(PDOException $e)
  {
   echo $e->getMessage(); 
   return false;
  }
 }
 
 public function delete($id)
 {
  $stmt = $this->db->prepare("DELETE FROM tbl_users WHERE id=:id");
  $stmt->bindparam(":id",$id);
  $stmt->execute();
  return true;
 }
 
 /* paging */
 
 public function dataview($query)
 {
  $stmt = $this->db->prepare($query);
  $stmt->execute();
 
  if($stmt->rowCount()>0)
  {
   while($row=$stmt->fetch(PDO::FETCH_ASSOC))
   {
    ?>
                <tr>
                <td><?php print($row['id']); ?></td>
                <td><?php print($row['first_name']); ?></td>
                <td><?php print($row['last_name']); ?></td>
                <td><?php print($row['email_id']); ?></td>
                <td><?php print($row['contact_no']); ?></td>
                <td align="center">
                <a href="edit-data.php?edit_id=<?php print($row['id']); ?>"><i class="glyphicon glyphicon-edit"></i></a>
                </td>
                <td align="center">
                <a href="delete.php?delete_id=<?php print($row['id']); ?>"><i class="glyphicon glyphicon-remove-circle"></i></a>
                </td>
                </tr>
                <?php
   }
  }
  else
  {
   ?>
            <tr>
            <td>Nothing here...</td>
            </tr>
            <?php
  }
  
 }
 
 public function paging($query,$records_per_page)
 {
  $starting_position=0;
  if(isset($_GET["page_no"]))
  {
   $starting_position=($_GET["page_no"]-1)*$records_per_page;
  }
  $query2=$query." limit $starting_position,$records_per_page";
  return $query2;
 }
 
 public function paginglink($query,$records_per_page)
 {
  
  $self = $_SERVER['PHP_SELF'];
  
  $stmt = $this->db->prepare($query);
  $stmt->execute();
  
  $total_no_of_records = $stmt->rowCount();
  
  if($total_no_of_records > 0)
  {
   ?><ul class="pagination"><?php
   $total_no_of_pages=ceil($total_no_of_records/$records_per_page);
   $current_page=1;
   if(isset($_GET["page_no"]))
   {
    $current_page=$_GET["page_no"];
   }
   if($current_page!=1)
   {
    $previous =$current_page-1;
    echo "<li><a href='".$self."?page_no=1'>First</a></li>";
    echo "<li><a href='".$self."?page_no=".$previous."'>Previous</a></li>";
   }
   for($i=1;$i<=$total_no_of_pages;$i++)
   {
    if($i==$current_page)
    {
     echo "<li><a href='".$self."?page_no=".$i."' style='color:red;'>".$i."</a></li>";
    }
    else
    {
     echo "<li><a href='".$self."?page_no=".$i."'>".$i."</a></li>";
    }
   }
   if($current_page!=$total_no_of_pages)
   {
    $next=$current_page+1;
    echo "<li><a href='".$self."?page_no=".$next."'>Next</a></li>";
    echo "<li><a href='".$self."?page_no=".$total_no_of_pages."'>Last</a></li>";
   }
   ?></ul><?php
  }
 }
 
 /* paging */
 
}

layouts

To reduce and make it less our code, we will create these two template files: header.php, footer.php
header.php
This header.php file will be included at the beginning of all files so that we won’t have to write the same header codes every-time. this file contains bootstrap file links.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PDO OOP CRUD using Bootstrap</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"> 
</head>

<body>

<div class="navbar navbar-default navbar-static-top" role="navigation">
    <div class="container">
 
        <div class="navbar-header">
            <a class="navbar-brand" href="http://www.codingcage.com" title='Programming Blog'>Coding Cage</a>
            <a class="navbar-brand" href="https://codingcage.com/search/label/CRUD">CRUD</a>
            <a class="navbar-brand" href="https://codingcage.com/search/label/PDO">PDO</a>
            <a class="navbar-brand" href="https://codingcage.com/search/label/jQuery">jQuery</a>
        </div>
 
    </div>
</div>

footer.php
This footer.php file will be included at the end of all files so that we won’t have to write the same footer codes every-time.

<div class="container">
 <div class="alert alert-info">
    <strong>tutorial !</strong> <a href="https://codingcage.com/">Coding Cage</a>!
 </div>
</div>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

index.php

this file will show the records from the mysql database with pagination feature. the table which are used in this file are created under bootstrap data table with class='table table-bordered table-responsive' it will make tables look pretty.

<?php
include_once 'dbconfig.php';
?>
<?php include_once 'header.php'; ?>

<div class="clearfix"></div>

<div class="container">
<a href="add-data.php" class="btn btn-large btn-info"><i class="glyphicon glyphicon-plus"></i> &nbsp; Add Records</a>
</div>

<div class="clearfix"></div><br />

<div class="container">
     <table class='table table-bordered table-responsive'>
     <tr>
     <th>#</th>
     <th>First Name</th>
     <th>Last Name</th>
     <th>E - mail ID</th>
     <th>Contact No</th>
     <th colspan="2" align="center">Actions</th>
     </tr>
     <?php
  $query = "SELECT * FROM tbl_users";       
  $records_per_page=3;
  $newquery = $crud->paging($query,$records_per_page);
  $crud->dataview($newquery);
  ?>
    <tr>
        <td colspan="7" align="center">
    <div class="pagination-wrap">
            <?php $crud->paginglink($query,$records_per_page); ?>
         </div>
        </td>
    </tr>
 
</table>
   
       
</div>

<?php include_once 'footer.php'; ?>

above code will give following output :

Data view Using PDO and OOP


add-data.php

now create a file and name it 'add-data.php' to get data from users to store into mysql database.
in this file some appropriate message are given about data are insert or not with bootstrap label.

<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
 $fname = $_POST['first_name'];
 $lname = $_POST['last_name'];
 $email = $_POST['email_id'];
 $contact = $_POST['contact_no'];
 
 if($crud->create($fname,$lname,$email,$contact))
 {
  header("Location: add-data.php?inserted");
 }
 else
 {
  header("Location: add-data.php?failure");
 }
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>

<?php
if(isset($_GET['inserted']))
{
 ?>
    <div class="container">
 <div class="alert alert-info">
    <strong>WOW!</strong> Record was inserted successfully <a href="index.php">HOME</a>!
 </div>
 </div>
    <?php
}
else if(isset($_GET['failure']))
{
 ?>
    <div class="container">
 <div class="alert alert-warning">
    <strong>SORRY!</strong> ERROR while inserting record !
 </div>
 </div>
    <?php
}
?>

<div class="clearfix"></div><br />

<div class="container">

  
  <form method='post'>
 
    <table class='table table-bordered'>
 
        <tr>
            <td>First Name</td>
            <td><input type='text' name='first_name' class='form-control' required></td>
        </tr>
 
        <tr>
            <td>Last Name</td>
            <td><input type='text' name='last_name' class='form-control' required></td>
        </tr>
 
        <tr>
            <td>Your E-mail ID</td>
            <td><input type='text' name='email_id' class='form-control' required></td>
        </tr>
 
        <tr>
            <td>Contact No</td>
            <td><input type='text' name='contact_no' class='form-control' required></td>
        </tr>
 
        <tr>
            <td colspan="2">
            <button type="submit" class="btn btn-primary" name="btn-save">
      <span class="glyphicon glyphicon-plus"></span> Create New Record
   </button>  
            <a href="index.php" class="btn btn-large btn-success"><i class="glyphicon glyphicon-backward"></i> &nbsp; Back to index</a>
            </td>
        </tr>
 
    </table>
</form>
     
     
</div>

<?php include_once 'footer.php'; ?>


this will create following form :

Insert Records Form using PDO OOP


edit-data.php

after creating a data insert form, this file updates the users data and the update operation are done by update() function which are define in 'class.crud.php' class file

<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-update']))
{
 $id = $_GET['edit_id'];
 $fname = $_POST['first_name'];
 $lname = $_POST['last_name'];
 $email = $_POST['email_id'];
 $contact = $_POST['contact_no'];
 
 if($crud->update($id,$fname,$lname,$email,$contact))
 {
  $msg = "<div class='alert alert-info'>
    <strong>WOW!</strong> Record was updated successfully <a href='index.php'>HOME</a>!
    </div>";
 }
 else
 {
  $msg = "<div class='alert alert-warning'>
    <strong>SORRY!</strong> ERROR while updating record !
    </div>";
 }
}

if(isset($_GET['edit_id']))
{
 $id = $_GET['edit_id'];
 extract($crud->getID($id)); 
}

?>
<?php include_once 'header.php'; ?>

<div class="clearfix"></div>

<div class="container">
<?php
if(isset($msg))
{
 echo $msg;
}
?>
</div>

<div class="clearfix"></div><br />

<div class="container">
  
     <form method='post'>
 
    <table class='table table-bordered'>
 
        <tr>
            <td>First Name</td>
            <td><input type='text' name='first_name' class='form-control' value="<?php echo $first_name; ?>" required></td>
        </tr>
 
        <tr>
            <td>Last Name</td>
            <td><input type='text' name='last_name' class='form-control' value="<?php echo $last_name; ?>" required></td>
        </tr>
 
        <tr>
            <td>Your E-mail ID</td>
            <td><input type='text' name='email_id' class='form-control' value="<?php echo $email_id; ?>" required></td>
        </tr>
 
        <tr>
            <td>Contact No</td>
            <td><input type='text' name='contact_no' class='form-control' value="<?php echo $contact_no; ?>" required></td>
        </tr>
 
        <tr>
            <td colspan="2">
                <button type="submit" class="btn btn-primary" name="btn-update">
       <span class="glyphicon glyphicon-edit"></span>  Update this Record
    </button>
                <a href="index.php" class="btn btn-large btn-success"><i class="glyphicon glyphicon-backward"></i> &nbsp; CANCEL</a>
            </td>
        </tr>
 
    </table>
</form>
     
     
</div>

<?php include_once 'footer.php'; ?>


delete.php

this file contains code for data delete operation using delete() function by passing id argument's value of selected data and row and by pressing the delete button the record will be deleted and message will be given that the record was deleted.

<?php
include_once 'dbconfig.php';

if(isset($_POST['btn-del']))
{
 $id = $_GET['delete_id'];
 $crud->delete($id);
 header("Location: delete.php?deleted"); 
}

?>

<?php include_once 'header.php'; ?>

<div class="clearfix"></div>

<div class="container">

 <?php
 if(isset($_GET['deleted']))
 {
  ?>
        <div class="alert alert-success">
     <strong>Success!</strong> record was deleted... 
  </div>
        <?php
 }
 else
 {
  ?>
        <div class="alert alert-danger">
     <strong>Sure !</strong> to remove the following record ? 
  </div>
        <?php
 }
 ?> 
</div>

<div class="clearfix"></div>

<div class="container">
  
  <?php
  if(isset($_GET['delete_id']))
  {
   ?>
         <table class='table table-bordered'>
         <tr>
         <th>#</th>
         <th>First Name</th>
         <th>Last Name</th>
         <th>E - mail ID</th>
         <th>Gender</th>
         </tr>
         <?php
         $stmt = $DB_con->prepare("SELECT * FROM tbl_users WHERE id=:id");
         $stmt->execute(array(":id"=>$_GET['delete_id']));
         while($row=$stmt->fetch(PDO::FETCH_BOTH))
         {
             ?>
             <tr>
             <td><?php print($row['id']); ?></td>
             <td><?php print($row['first_name']); ?></td>
             <td><?php print($row['last_name']); ?></td>
             <td><?php print($row['email_id']); ?></td>
           <td><?php print($row['contact_no']); ?></td>
             </tr>
             <?php
         }
         ?>
         </table>
         <?php
  }
  ?>
</div>

<div class="container">
<p>
<?php
if(isset($_GET['delete_id']))
{
 ?>
   <form method="post">
    <input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
    <button class="btn btn-large btn-primary" type="submit" name="btn-del"><i class="glyphicon glyphicon-trash"></i> &nbsp; YES</button>
    <a href="index.php" class="btn btn-large btn-success"><i class="glyphicon glyphicon-backward"></i> &nbsp; NO</a>
    </form>  
 <?php
}
else
{
 ?>
    <a href="index.php" class="btn btn-large btn-success"><i class="glyphicon glyphicon-backward"></i> &nbsp; Back to index</a>
    <?php
}
?>
</p>
</div> 
<?php include_once 'footer.php'; ?>

above code for deletion gives following output :

Confirmation on Record Delete


if the record was deleted the output will be as follow :

Record was Deleted Message

that’s it we have created here Simple PDO CRUD Operation using OOP with Bootstrap framework with pagination feature.
download the script by clicking following link and try it in your projects.
Feel free to comment your suggestions regarding this tutorial.



115 comments:

  1. looks good using bootstrap, nice tutorial

    ReplyDelete
  2. Very good stuff. Thanks a lot.

    ReplyDelete
  3. very nice script, with all, so use PDO for PHP and use bind of variables style JAVA prepared statements.
    Thank you so much...

    ReplyDelete
  4. Change contact_no in MySQL from int to bigint, and everything starts working.

    ReplyDelete
  5. Gracias por el código.

    ReplyDelete
  6. Nice script! Although, if you keep ?inserted at the end of url and hit submit without a field you get blank in db.. I would put ... if (empty($_POST['example'] || etc, etc)) { header("Location: index.php?failure"); } else { $example = $_POST['example']}inside the if(isset($_POST['btn-save'])) to prevent this.

    ReplyDelete
  7. It is nice to work with, but not safe so, because you can fill out all input fields in the what ever you want, such as, for example, niek# hotmail.com or [email protected]@hotmail.com

    ReplyDelete
  8. I have those other links below once viewed and tried out.
    But when I put a patern as below in the input field then put that doesn't work in this PDO script

    input type='text' pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" name='email_id' class='form-control' required

    ReplyDelete
    Replies
    1. try the following, it works

      <input type='email' pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" name='email_id' class='form-control' required>

      Delete
  9. Thanks that works.
    Only one more question: why email_id and email.
    I ask that because I already have a registration script, with a user_id, user_name, user_email and user_password, But that has no edit and delette script.
    And that's why I use now this Grud script

    ReplyDelete
    Replies
    1. you can change "email_id" into "user_email" and
      <input type="email" />
      well it's a new HTML5 attribute

      Delete
  10. could not find driver
    Fatal error: Call to a member function prepare() on a non-object in C:\AppServ\www\poo\class.crud.php on line 16

    porq este error ??????

    ReplyDelete
    Replies
    1. open "php.ini" file of your localhost server and
      find for ";extension=php_pdo_mysql.dll" and remove the
      semi-colon then save file and restart your server it enables PDO Driver.

      Delete
  11. Great beginning php tutorials Very clear and helpful for beginners.

    ReplyDelete
  12. Thank you for this tutorial. For someone that has to re-learn PHP as several functions (like mysql_connect) no longer work in the newest version of PHP, this has helped me quite a bit. I do have a couple questions though. When adding a phone number in U.S. format (XXX-XXX-XXXX), only the first 3 numbers are added to the database but the first dash and everything behind it is not added. I've been trying to figure out why, but I'm kind of stumped. Any ideas? Also any tips on adding a search function?

    ReplyDelete
  13. Ahh, I figured out why the phone number wasn't doing the dashes. Changed the MySQL table BIGINT to VARCHAR and it saves correctly now.

    ReplyDelete
  14. Nice blog...Very useful information is providing by ur blog. Great beginning php tutorials Very clear and helpful for beginners.

    ReplyDelete
  15. Hi, I posted a comment in your tutorial Simple PHP CRUD Operations.I think i should have posted it here instead. My question is, how do i add images and pdf's to the crud operations. I want the user to upload images and pdf's and save them in folders. I tried combining this tutorial with http://cleartuts.blogspot.com/2014/12/simple-file-uploading-with-php.html but wasn't successful. Thank you and i really like your tutorials. Great work :)

    ReplyDelete
    Replies
    1. combining these two things is easy, just alter your mysql table and add image, pdf file fields to the table and make change in sql insert query as i showed in following tutorial :

      https://codingcage.com/2014/12/file-upload-and-view-with-php-and-mysql.html

      Delete
    2. it is easy up to the point where the folder comes in.I am confused as to how and where some of the code from the file upload tutorial will fit into the php-pdo-crud-tutorial. This is what i have so far. Thank you. I really appreciate your help.


      create($first_name,$last_name,$gender, $student_phone_number, $parent_phone_number, $student_email, $course, $admission_type, $qualification))
      {
      $sql="INSERT INTO students(file,type,size) VALUES('$final_file','$file_type','$new_size')";
      mysql_query($sql);
      header("Location: add-data.php?inserted");
      }
      else
      {
      // header("Location: add-data.php?failure");
      echo "string";

      }
      }
      ?>

      Delete
  16. Have available the code to integrate search functionality? Thank you.

    ReplyDelete
    Replies
    1. I'll post a tutorial about it soon

      Delete
  17. Rally awesome tutorial, very well!
    I also see your login tutorial, how to apply your login to this?
    Thanks.

    ReplyDelete
  18. Hello everybody !

    Thank you very much for this job very well explained, being a novice in php coding, I have a comment,

    Pagination displays all the page numbers, it is a big disadvantage when we have a database with 1000 line,

    Because with 1000 lines in database, if we want to see 10 lines per page, there will be 100 pages number in the paging bar,

    Can we add some settings in the paging function to limit the number of links (number of pages) displayable in the pagination bar?

    Best regards.

    ReplyDelete
    Replies
    1. did you mean page no as query string in address bar if so , then we can use jquery ,ajax to paginate all the records ...

      Delete
    2. Hi Pradeep !

      In my case I have for example 1000 records (rows) in the database
      The only config parameter for the function is : "$records_per_page=X;"
      With "$records_per_page=10;" there will be 100 page links in the paging bar, it's a lot
      I asked i you cas improve the function by limiting the number of page links displayed

      Cordially, Hafid.

      Delete
  19. Rally awesome tutorial, very well!
    I also see your login tutorial, how to apply your login to this?
    Thanks.

    ReplyDelete
  20. How i can do radio insert, file gen male or female?

    ReplyDelete
    Replies
    1. try the following example :

      <?php
      if(isset($_POST['btn']))
      {
      echo $_POST['gen'];
      }
      ?>
      <form method="post">
      <label>Male <input type="radio" name="gen" value="Male" /></label>
      <label>FeMale <input type="radio" name="gen" value="FeMale" /></label>
      <button type="submit" name="btn">print</button>
      </form>

      Delete
  21. Hello !
    Really good works !
    But i've got a problem :) I've changed an "input" with a "textarea"... "Insert" and "delete" works fine.. but with "edit" the textarea is blank ! Where is the problem ?
    Thanks

    ReplyDelete
    Replies
    1. hi there,
      within textarea <textarea name="txt_area"> put here php code </textarea> while editing

      Delete
  22. Where do the variables that you echo out in the update section? I don't see $first_name, $last_name, etc.. being set anywhere. Not sure where you got them.. Can someone explain?
    Thx

    ReplyDelete
    Replies
    1. hello laslomcd,
      these variables are extracted using extract() function and within class.crud.php file "extract($crud->getID($id))" function returns edited rows from database.

      Delete
  23. Hello thanks for your Best crud...but what are the modification for putting edit and delete form in a Popup ?thankssss

    ReplyDelete
    Replies
    1. hello heyhooo, i will make a tutorial about it soon, keep visiting :)

      Delete
  24. Hello...How can I add a button to select all rows for example in order to delete multiple rows....thankkssss

    ReplyDelete
    Replies
    1. Hi HeyHooo, this article might help you to delete multiple rows
      multiple update delete using php mysql

      Delete
  25. Thxx for all!
    The "problem" is about the code: mysqli in one and Pdo in the other....can I use your First crud (multiple) without putting Pdo ?

    ReplyDelete
    Replies
    1. yes you can use, without using pdo

      Delete
  26. ...because the multiple delete,update,....is really wonderfull!...but for more "security" a confirmation before delete (like in ur CRUD PDO oop) is necessary...so, for u, can I use ur First multiple CRUD without re-coding all With Pdo ?(ps: I use already phpmyadmin)

    ReplyDelete
    Replies
    1. hi heyhooo, you can use both, without re-coding, you can use pdo or mysqli, crud concept was same they are only improved extensions .

      Delete
  27. tutorial is really nice and useful .. only two thing I want to know is what does this means
    "bindparam(":fname",$fname);"
    1-bindparam
    2-colon(":").
    I will be grateful if you explain those two things.. I am relatively new so there is confusion in it.

    ReplyDelete
    Replies
    1. hello taj,

      bindparam(":fname",$fname);

      1 bindParam — Binds a parameter to the specified variable name
      2 colon -- specifies the column which are declared in bindParam(),

      well you can also use this

      bindParam('val', $value, PDO::PARAM_STR);

      click here to know more

      Delete
  28. i will give it a try , thank for the code, greetings from el salvador.

    ReplyDelete
  29. Hello,
    Everything works fine for me, but i've changed a "input" with a "textarea" with a wysiwyg...and now, i've got html tags in my database... how can i delete these html tags in PDO ?

    ReplyDelete
    Replies
    1. Hello cetmol,
      sorry for the late reply and use htmlspecialchars(); function to convert html elements to special characters

      Delete
  30. Congratulations on the job , a question if possible .
    How can I insert a button print on the edit-data.php , to pass parameters to a page xxx.php ( html2pdf ) to generate a page pdf data ??
    thank you

    ReplyDelete
  31. how can i get bootstrap for my template

    ReplyDelete
  32. Hi Thank You for posting these posts your code is work perfectly
    but i have one problem i was added some ID it's work when i ad New record but when i try to update name contact number it's come blank field
    $id = $_GET['edit_id'];
    $fname = $_POST['first_name'];
    $lname = $_POST['last_name'];
    $email = $_POST['email_id'];
    $emp_dep = $_POST['emp_dep'];
    $emp_sal = $_POST['emp_sal'];
    $login_id = $_POST['login_id'];
    $pass = $_POST['pass'];
    $contact = $_POST['contact_no'];

    if($crud->update($id,$fname,$lname,$email,$emp_dep,$emp_sal,$login_id,$pass,$contact))

    ReplyDelete
    Replies
    1. Got the same problem, did you find a way to fix it?

      Delete
  33. download botton doesn't work

    ReplyDelete
    Replies
    1. Updated, working now ... download it ...

      Delete
  34. Hi Pradeep, very good script, thank you. An excellent enhancement to this would be to use a bootstrap modal and call the add-data.php and edit-data.php etc. I've tried and posted on stackoverflow but not getting the answers. Any chance you could do this for us?

    ReplyDelete
  35. Hi Pradeep, very good script, thank you. An excellent enhancement to this would be to use a bootstrap modal and call the add-data.php and edit-data.php etc. I've tried and posted on stackoverflow but not getting the answers. Any chance you could do this for us?

    ReplyDelete
    Replies
    1. hey james, i will post modal window crud with php tutorial soon ...

      Delete
  36. Mr. Khodke
    This is a nice tutorial blog. Could you help me with code in PDP MySQL in OOPHP to upload file.
    Thanks

    ReplyDelete
    Replies
    1. i will post file uploading tutorial using PHP PDO with OOP ....

      Delete
    2. Mr. Khodke,
      Could the post as needed be posted immediately? If it would be possible it would be really very helpful for me. Good night.

      Delete
  37. Mr Khodke,
    Thank you again for the wonderful tutorial. How to add image to mysql table in this script? Could you help?

    ReplyDelete
    Replies
    1. Hello Bishwajit,
      just alter your table and add new field for image and add code for image uploading with insert query,
      here is file uploading code : file upload with php mysql

      Delete
    2. The image insertion , update and delete should happen in php mysql pdo environment

      Delete
  38. Hello..
    Nice tutorials and thanks, greetings from Indonesia.

    ReplyDelete
  39. Replies
    1. thanks jordan... do visit again :)

      Delete
  40. Are you able to unit test this, if so how?

    ReplyDelete
  41. very useful example, exactly what I was looking for - many thanks.

    ReplyDelete
  42. Very cool script...EXACTLY what I've been searching for and trying to acheive for several weeks now. I have 7 different test sites that I have been trying accomplish the same thing on, problem is, every tutorial throws errors and I have NO CLUE how to fix them. This tut is no different. Getting undefined variables in dbcrud file and Fatal error: Call to a member function prepare() on null. I don't want the answer to these, I want to know how to fix these myself. Any suggestions, PLEASE????

    ReplyDelete
  43. Hallo admin ..

    previously thank you for sharing script free PDO. This is very cool.

    I added in the database UNIQUE USERS hopes that could not make anything duplicate with others.

    For example, I edit the username as 'Admin' which have previously been stored in the database with another account.

    In fact, USERS can not change their name to Admin, however, ERROR messages that appear unsightly.
    Like this:

    SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'Admin' for key 'uname'

    How to change the error message?

    ReplyDelete
  44. Interesting example, but based on the date of the post,I am surprised that you show it using mySql database connections and not PDO when mySql has been deprecated for several years. At the very least the database connections should be in mySqli. Also as a DB programmer, I would always try to use '?' for params in your query strings for safety/security reasons.
    Do you have updated code for this example?

    ReplyDelete
    Replies
    1. hi there, why are you surprised, i have just used here PDO extension to Perform CRUD operations with OOP way, and my friend mysql query(extension) is deprecated from several years the PDO extension is improved mysql extension it is a database layer and it also prevent sql injections cause there are prepare, bindparam and execute statements and methods.

      Delete
  45. Hi Pradeep,
    i have add a column name "status" at tbl_users. the value is 0 and 1. i want to data on,ly have status = 1. How to code ?

    sorry my english :)

    ReplyDelete
  46. Hi, I found this error both when I try to re-write them by myself and use the script I've downloaded:

    Fatal error: Uncaught Error: Call to a member function prepare() on string in C:\xampp\htdocs\CRUD2\class.crud.php:71 Stack trace: #0 C:\xampp\htdocs\CRUD2\index.php(27): crud->dataview('SELECT*FROM tbl...') #1 {main} thrown in C:\xampp\htdocs\CRUD2\class.crud.php on line 71

    The line for C:\xampp\htdocs\CRUD2\class.crud.php:71 is:
    $stmt = $this->db->prepare($query);

    and for C:\xampp\htdocs\CRUD2\index.php(27):
    $crud->dataview($newquery);


    Can you please tell me that this error mean?
    Thank you.

    ReplyDelete
  47. Interesting article. I really enjoyed reading entire page content. PDO is very better in use in PHP. The article is so clear to understand crud. http://www.phptutorials.club

    ReplyDelete
  48. sir / ma'am

    can i use this for my project?
    is there anything i need so i can able to use this for free?

    ReplyDelete
  49. sir gud day,

    i like ur tutorial

    if ok sir, i u want to use this for my projct?
    is there anything i need to be able to use this for free?

    ReplyDelete
    Replies
    1. Hi Bon...
      glad you liked it, you can use it freely ... :)

      Delete
  50. How to have user also as a class

    ReplyDelete
  51. How to have User also as one class

    ReplyDelete
  52. Hi Pradeep...Thank You very much for all your perfectly tested examples. These are very useful and the way you explained these is great.

    I am new to php and using your CRUD example. i am just trying to update record of another table based on the id displayed by this example but it is throwing error..."[SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens]".

    Actually i have two table one is "tbl_users" table and other is "two2" based on the id in "tbl_users" table i have to update the "two2" table data. I am just trying to fit your example for this.

    Any help please....
    The code is like this...
    .............
    //update tran table
    public function update2($id,$ref,$name,$amount,$remarks,$date,$remark2,$int1,$int2,$date2)
    {
    try
    {

    $stmt=$this->db->prepare("UPDATE two2 SET ref=:id,
    name=:name,amount=:amount,remarks=:remarks,date=date,remark2=remark2,int1=int1,
    int2=int2,date2=date2 WHERE ref=:id ");
    $stmt->bindparam(":ref",$id);
    $stmt->bindparam(":name",$name);
    $stmt->bindparam(":amount",$amount);
    $stmt->bindparam(":remarks",$remarks);
    $stmt->bindparam(":date",$date);
    $stmt->bindparam(":remark2",$remark2);
    $stmt->bindparam(":int1",$int1);
    $stmt->bindparam(":int2",$int2);
    $stmt->bindparam(":date2",$date2);
    $stmt->bindparam(":id",$id);
    $stmt->execute();

    return true;
    }
    catch(PDOException $e)
    {
    echo $e->getMessage();
    return false;
    }
    }

    ....................-----------------------


    edit-data.php
    .....
    include_once 'dbconfig.php';
    if(isset($_POST['btn-update']))
    {
    //$id = $_GET['id'];
    $id = $_GET['edit_id'];
    $ref = $_POST['ref'];
    $name = $_POST['name'];
    $amount = $_POST['amount'];
    $remarks = $_POST['remarks'];
    $date = $_POST['date'];
    $remark2 = $_POST['remark2'];
    $int1 = $_POST['int1'];
    $int2 = $_POST['int2'];
    $date2 = $_POST['date2'];



    if($crud->update2($id,$ref,$name,$amount,$remarks,$date,$remark2,$int1,$int2,$date2))
    {

    ReplyDelete
  53. good thanks for this excellent tutorial, as you would to add a search field in the index

    ReplyDelete
  54. Hi pradeep, i have done it. thanks

    ReplyDelete
  55. could you please help how to use drop down box in this example to filter records(index.php)

    ReplyDelete
  56. Hi,
    How would i use this multiple times on 1 page? For example i would like to extract data from the database and display the data based on different queries in 3 tables in a single php page. Im guessing it would involve adding to the class file as i've tried changing the variable names to $query2, $crud2 etc for the second table but nothing is displayed.

    ReplyDelete
  57. Thank you.
    I gathered much needed info.
    Great tutorial!

    ReplyDelete
  58. Can we use the GetId method to show an individual record in non-edit mode?
    "public function getID($id)"

    ReplyDelete
  59. Do you have an example like this but accessing a MSAccess Database using PDO?

    ReplyDelete
    Replies
    1. So long as you have the database in the structure shown and the PDO connector for MSAccess, if there is one, you should be good to go. That's the beauty of PDO; change the database and connector; the rest stays the same. Access previously used MickeySoft connectors RDO and ADO...much similar.
      Amazed to hear someone still using Access.

      Delete
  60. oh wow!! thanks a lot :)

    ReplyDelete
  61. i have found such a great material from your blog,
    Thanks for sharing with us,.
    image uploader

    ReplyDelete
  62. Sir how about search engine attached in tables. Can give us samples. im using pdo extension with php 7.. thank you..

    ReplyDelete
  63. Hi, thanks lot for your job. I have make a generator crud pdo for based this tuto. your can tested here : http://generator-crud-pdo.890m.com/

    see you all !

    ReplyDelete
    Replies
    1. Hi Le,
      thanks for the crud generator, you did a great job...

      Delete
  64. how if I use dbconfig.php like this?
    conn = null;
    try
    {
    $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
    $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $exception)
    {
    echo "Connection error: " . $exception->getMessage();
    }

    return $this->conn;
    }
    }
    ?>

    ReplyDelete
  65. Hi there if i have many tables how can i use the crud class?

    I need to have a class configured to each form?

    ReplyDelete
  66. Many thanks! Great you save me a lot of work and time to learn.

    Can you inform me if we can create a list a values for a filed, based on DB table records?
    For example I would like to have a
    -field Menu, which take values from table t_Menu
    - user selects a value and moves to the next field SubMenu
    - now the values on the list that will appear, must be filtered based on the value selected from Menu field

    Thanks

    ReplyDelete
  67. Many thanks! Great you save me a lot of work and time to learn.

    Can you inform me if we can create a list a values for a filed, based on DB table records?
    For example I would like to have a
    -field Menu, which take values from table t_Menu
    - user selects a value and moves to the next field SubMenu
    - now the values on the list that will appear, must be filtered based on the value selected from Menu field

    Thanks

    ReplyDelete
  68. Hi everyone,

    Many thanks for your tutorial, PRADEEP KHODKE!

    When I run this project I saw the following message:
    Fatal error: Cannot declare class crud, because the name is already in use in ..../class.crud.php on line 3 which is:
    class crud

    Is necessary to reset a CRUD object which have been previously created?

    Thanks in advance. Best regards.

    ReplyDelete
  69. Dear sir,
    "id" field not want to auto. how to update "id" field

    ReplyDelete
  70. Really nice examples. Thank you very much. However, to print out the table
    I would rather loop through the keys of the $row array. (My database contains
    more fields). I am not very familiar with OOP, so bear with me for a stupid question: in OOP PHP, do I write a loop like


    (I removed < and > from the code because the tag is not allowed.)
    as in the good old php, or would there be a better way?

    ReplyDelete
  71. Congratulations for this great tutorial i'm happy to bump into it.
    I created an new table by following the code process to add new data, unfortunately i have this message in this code part in add-data.php file :

    ERROR while inserting record !

    db->errorInfo()))
    so that i can display and see what the error is about?
    thanks

    ReplyDelete
  72. Again i'm back to this nice tuto, i try to add die(print_r($DB_con->errorInfo(), true)); in add-data.php file after ERROR while inserting record !. As result i get this message :
    Array ( [0] => 00000 [1] => [2] => )
    How to display the error information so that i can debbug ?

    ReplyDelete
  73. Hi Bro Pradep, thank you very much for sharing this great tutorial! :D
    it's clear explained and easy to follow. Keep posting something great like this.

    Oh yea, do you have some good references tutorial for create REST API data exchange from PHP to JSON for Ionic ?

    Best regards

    ReplyDelete
  74. Great tutorial my friend... thank you very much!! One little question, how do you handle this using a Login form to prevent the use for a non registered users? hope that you can make an example on this :)

    ReplyDelete
    Replies
    1. Hey KIEV, it's simple, just make crud pages with session so that only logged in users can access it, BTW thanks for the suggestion i'll post tutorial on it very soon :)

      keep visiting ....

      Delete