CRUD Operations in PHP with PDO using Bootstrap - onlyxcodes

Sunday, 31 March 2019

CRUD Operations in PHP with PDO using Bootstrap

In this tutorial, I'll use Bootstrap to show you CRUD (Create, Read, Update, Delete) operations in PHP with PDO.

When you first build a PHP website you must learn CRUD operations which is a normal or common task for any web application or website.

If you don’t know how to make a CRUD operation in PHP. You'll be master of the CRUD application after learning these tutorial source codes and you can quickly import these codes into any dynamic website.

I have used PDO's latest extension of PHP in this tutorial. If you don't know about the principle of PDO, this tutorial has quickly solved your PDO-related question, PDO benefits, how to allow PDO drivers, and provides useful guidance. Go have a quick look and a ton of easy tutorials.

Learn More:





CRUD Operations in PHP with PDO using Bootstrap

Table Content

1. About PDO [ PHP Data Object ]

    1.1 Benefits To Use PDO

    1.2 How To Enable PDO Driver

2. Needed Tools

3. Project Set-Up In XAMPP Server

4. Database / Table Creating

5. Database Connection Utility

6. index.php [ read records ]

7. add.php [ create/insert records ]

    7.1 PHP Insert Code With PDO

8. edit.php [ update records ]

    8.1 PHP Update Code With PDO

9. PHP Delete Code With PDO


1. About PDO [ PHP Data Object ]

PDO set up below in the fifth edition of PHP implementing MySQL extension. Its driver did not only allow access to MySQL to open multiple database connections Oracle, ODBC, Microsoft SQL Server, SQLite, PostgresSQL, and more.

1.1 Benefits To Use PDO : -


  • PDO provides its features prepared statements that use this to decrease attacks on SQL injection.

  • PDO provides the built-in bindParam() and bindValue() function. The bindParam() function binds the placeholder of the parameter in the SQL query that holds a specific variable. The bindValue() function binds the value that the integer, string, and variables can specify.

  • PDO extension is comparable slightly with other extensions and a great performer in the object-oriented approach.

  • Now present time PHP programmer does not use the deprecated MySQL extension MySQL and MySQLi. They all forward to PDO.

1.2 How To Enable PDO Driver : -


Go to the php.ini configuration file and enable the PDO extension driver.

;extension=php_pdo_mysql.dll 

remove the semi column.

extension=php_pdo_mysql.dll 

2. Needed Tools

Bootstrap – Download. Using bootstrap plugin this tutorial design form, tables, buttons, etc for better UI/UX experience.

XAMPP – Download. This project set up and execute in the XAMPP server.

Notepad++ – Download. This project all source code developed in this editor.

3. Project Set-Up In XAMPP Server

I assume to have a XAMPP server installed. I set up this project in C:\xampp\htdocs\Insert-Update-Delete-PHP-PDO path place, as I have the XAMPP server installed in C: drive. See the project directory below. 


Project Directory Structure of CRUD Operations in PHP

4. Database / Table Creating 

Import the following SQL code to develop a database and table to store the first name and last name of the person fields. 

--
-- Database: `php_pdo_crud_db`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_person`
--

CREATE TABLE `tbl_person` (
  `id` int(11) NOT NULL,
  `firstname` varchar(15) NOT NULL,
  `lastname` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Make a person named table in MySQL database

After developing a database, we need to make the following PHP files: 

index.php – Retrieve [read] records in this file from MySQL table. 

connection.php – Open connection of MySQL database to PDO extension in this file. 

add.php – In this file insert [create] new person records in a table. 

edit.php – Edit [update] records of a particular person in this file. 

5. Database Connection Utility

Simple and Quick Database setup code of PDO extension, modify the below file according to your database credentials and save its name according to your criteria.

<?php
$db_host="localhost"; //localhost server 
$db_user="root"; //database username
$db_password=""; //database password   
$db_name="php_pdo_crud_db"; //database name

try
{
 $db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
 $e->getMessage();
}

?>

6. index.php [ read records ]

First of all, start CRUD operations to retrieve fresh data from the MySQL person table and set this design by bootstrap into table format. 

<table class="table table-striped table-bordered table-hover">
    <thead>
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
    </thead>
    <tbody>
 <?php
 $select_stmt=$db->prepare("SELECT * FROM tbl_person"); //sql select query
 $select_stmt->execute();
 while($row=$select_stmt->fetch(PDO::FETCH_ASSOC))
 {
 ?>
        <tr>
            <td><?php echo $row['firstname']; ?></td>
            <td><?php echo $row['lastname']; ?></td>
            <td><a href="edit.php?update_id=<?php echo $row['id']; ?>" class="btn btn-warning">Edit</a></td>
            <td><a href="?delete_id=<?php echo $row['id']; ?>" class="btn btn-danger">Delete</a></td>
        </tr>
    <?php
 }
 ?>
   </tbody>
</table> 

Read Data from the Database and Set-Up in a Bootstrap Table

7. add.php [ create / insert records ]

Simple HTML form make with bootstrap, first name and last name are the fields I took here for a person.

<?php
if(isset($errorMsg)){
?>
    <div class="alert alert-danger">
        <strong>WRONG ! <?php echo $errorMsg; ?></strong>
    </div>
<?php
}
if(isset($insertMsg)){
?>
 <div class="alert alert-success">
  <strong>SUCCESS ! <?php echo $insertMsg; ?></strong>
 </div>
<?php
}
?>
<form method="post" class="form-horizontal">
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Firstname</label>
 <div class="col-sm-6">
 <input type="text" name="txt_firstname" class="form-control" placeholder="enter firstname" />
 </div>
 </div>
      
 <div class="form-group">
 <label class="col-sm-3 control-label">Lastname</label>
 <div class="col-sm-6">
 <input type="text" name="txt_lastname" class="form-control" placeholder="enter lastname" />
 </div>
 </div>
   
 <div class="form-group">
 <div class="col-sm-offset-3 col-sm-9 m-t-15">
 <input type="submit"  name="btn_insert" class="btn btn-success " value="Insert">
 <a href="index.php" class="btn btn-danger">Cancel</a>
 </div>
 </div>
     
</form>

Insert Form :


PHP Insert Form for Create New Data in Database

7.1 PHP Insert Code With PDO


Add the below PHP script beginning above the <! DOCTYPE html> tag. A person's first name and last name will be inserted in this script. If any failure has arisen, the bootstrap alert will display a relevant message.

<?php

require_once "connection.php";

if(isset($_REQUEST['btn_insert']))
{
 $firstname = $_REQUEST['txt_firstname']; //textbox name "txt_firstname"
 $lastname = $_REQUEST['txt_lastname']; //textbox name "txt_lastname"
  
 if(empty($firstname)){
  $errorMsg="Please Enter Firstname";
 }
 else if(empty($lastname)){
  $errorMsg="Please Enter Lastname";
 }
 else
 {
  try
  {
   if(!isset($errorMsg))
   {
    $insert_stmt=$db->prepare('INSERT INTO tbl_person(firstname,lastname) VALUES(:fname,:lname)');      
    $insert_stmt->bindParam(':fname',$firstname);
    $insert_stmt->bindParam(':lname',$lastname);   
     
    if($insert_stmt->execute())
    {
     $insertMsg="Insert Successfully........"; 
     header("refresh:3;index.php"); 
    }
   }
  }
  catch(PDOException $e)
  {
   echo $e->getMessage();
  }
 }
}

?>

8. edit.php [ update records ]

The editing form is as simple as bootstrap designing an insert form. When you press the edit hyperlink, this form will obtain specific data for editing from the database.

<?php
if(isset($errorMsg)){
?>
    <div class="alert alert-danger">
        <strong>WRONG ! <?php echo $errorMsg; ?></strong>
    </div>
<?php
}
if(isset($updateMsg)){
?>
 <div class="alert alert-success">
  <strong>UPDATE ! <?php echo $updateMsg; ?></strong>
 </div>
<?php
}
?>
<form method="post" class="form-horizontal">
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Firstname</label>
 <div class="col-sm-6">
 <input type="text" name="txt_firstname" class="form-control" value="<?php echo $firstname; ?>">
 </div>
 </div>
     
 <div class="form-group">
 <label class="col-sm-3 control-label">lastname</label>
 <div class="col-sm-6">
 <input type="text" name="txt_lastname" class="form-control" value="<?php echo $lastname; ?>">
 </div>
 </div>
      
 <div class="form-group">
 <div class="col-sm-offset-3 col-sm-9 m-t-15">
 <input type="submit" name="btn_update" class="btn btn-primary" value="Update">
 <a href="index.php" class="btn btn-danger">Cancel</a>
 </div>
 </div>
   
</form>

Update Form :


PHP Update Form for Updating Existing Data in Database

8.1 PHP Update Code With PDO


Again underneath PHP update codes begin before <! DOCTYPE html > tag in file 'update.php'. If data is selected for editing then old records will be removed and person new records updated, the same PHP script here's.

 <?php

require_once "connection.php";

if(isset($_REQUEST['update_id']))
{
 try
 {
  $id = $_REQUEST['update_id']; 
  $select_stmt = $db->prepare('SELECT * FROM tbl_person WHERE id =:id'); 
  $select_stmt->bindParam(':id',$id);
  $select_stmt->execute(); 
  $row = $select_stmt->fetch(PDO::FETCH_ASSOC);
  extract($row);
 }
 catch(PDOException $e)
 {
  $e->getMessage();
 }
 
}

if(isset($_REQUEST['btn_update']))
{
 
 $firstname_up = $_REQUEST['txt_firstname']; //textbox name "txt_firstname"
 $lastname_up = $_REQUEST['txt_lastname']; //textbox name "txt_lastname"
  
 if(empty($firstname_up)){
  $errorMsg="Please Enter Firstname";
 }
 else if(empty($lastname_up)){
  $errorMsg="Please Enter Lastname";
 } 
 else
 {
  try
  {
   if(!isset($errorMsg))
   {
    $update_stmt=$db->prepare('UPDATE tbl_person SET firstname=:fname_up, lastname=:lname_up WHERE id=:id'); 
    $update_stmt->bindParam(':fname_up',$firstname_up);
    $update_stmt->bindParam(':lname_up',$lastname_up); 
    $update_stmt->bindParam(':id',$id);
     
    if($update_stmt->execute())
    {
     $updateMsg="Record Update Successfully......."; 
     header("refresh:3;index.php"); 
    }
   } 
  }
  catch(PDOException $e)
  {
   echo $e->getMessage();
  } 
 } 
}
?>



Friends Here,

I highly recommend that you learn the course below. In this course To comprehensively understand CRUD codes and PDO depth.


It is the best course of the highest rating, Mr. Terry Ogbemudia Osayawe will teach you to step by step this course both beginners and experienced web developers will gain a comprehensive understanding of the modern PDO extension and how it can be used to create scalable database driven application.

Here is the key skill you'll become learning in this course.

1. In-depth understanding of PHP Data Object (PDO)

2. Protect any web application against SQL Injection

3. Build a Basic Task List with PDO, PHP, and MySQL

4. Perform CRUD (Create, Read, Update and Delete) Operations with PHP Data Object (PDO) including with jQuery Ajax

5. Send Request via Ajax without page Refresh

6. Dealing with Errors in PHP Data Object (PDO)

7. Pagination, Validate Form Data using Ajax, and also Bonus Lecture.

More students are enrolled in this course and they are now improving their existing skills. wrap it up now.




9. PHP Delete Code With PDO

Now Placed the delete code simply over <! DOCTYPE html > tag inside the file 'index.php'. Clicking on a particular delete hyperlink will then forever data deleted from the database.

<?php

require_once "connection.php";
 
if(isset($_REQUEST['delete_id']))
{
 // select record from db to delete
 $id=$_REQUEST['delete_id']; //get delete_id and store in $id variable
  
 $select_stmt= $db->prepare('SELECT * FROM tbl_person WHERE id =:id'); //sql select query
 $select_stmt->bindParam(':id',$id);
 $select_stmt->execute();
 $row=$select_stmt->fetch(PDO::FETCH_ASSOC);
  
 //delete an orignal record from db
 $delete_stmt = $db->prepare('DELETE FROM tbl_person WHERE id =:id');
 $delete_stmt->bindParam(':id',$id);
 $delete_stmt->execute();
  
 header("Location:index.php");
}
 
?>




Download Codes

No comments:

Post a comment