June 30, 2014 10:51 am

PHP CRUD with Twitter Bootstrap 3 Part – 2/2

PHP CRUD This is the 2nd part of CRUD tutorial in this part we will cover “Read“, “Update” and “Delete“options in our previously created grid in tutorial part 1. I will give you its complete demo and a source code to download free so you can try that in your own websites.

PHP CRUD with Twitter Bootstrap Part - 2

[wpdm_file id=105]DEMO

Read: PHP CRUD with Twitter Bootstrap 3 Part – 1/2

We have already created create option in our previous part after adding a record our grid looks like this:

PHP CRUD Main page part 2

Create Read page

Create a page “read.php” and add in your CRUD directory, this file used to give read functionality to you CRUD system.

<?php 
    require 'db.php';
    $id = null;
    if(!empty($_GET['id']))
    {
        $id = $_GET['id'];
    }
    if($id == null)
    {
        header("Location: index.php");
    }
    else
    {
        $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM users where id = ?";
        $stmt = $PDO->prepare($sql);
        $stmt->execute(array($id));
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        $PDO = null;
        if (empty($data)){
            header("Location: index.php");
        }
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>
 
<body>
<div class="container">
    <div class="col-sm-12">
        <div class="row">
            <h3>Read a User</h3>
        </div>
            
        <div class="form-group col-sm-12">
            <label class="col-sm-2 control-label">First Name</label>
            <div class="col-sm-10">
              <p class="form-control-static"><?php echo $data['FName'];?></p>
            </div>
        </div>
        <div class="form-group col-sm-12">
            <label class="col-sm-2 control-label">Last Name</label>
            <div class="col-sm-10">
              <p class="form-control-static"><?php echo $data['LName'];?></p>
            </div>
        </div>
        <div class="form-group col-sm-12">
            <label class="col-sm-2 control-label">Age</label>
            <div class="col-sm-10">
              <p class="form-control-static"><?php echo $data['Age'];?></p>
            </div>
        </div>
        <div class="form-group col-sm-12">
            <label class="col-sm-2 control-label">Gender</label>
            <div class="col-sm-10">
              <p class="form-control-static"><?php echo $data['Gender'];?></p>
            </div>
        </div>
        <div class="form-group col-sm-12">
            <a class="btn btn btn-default" href="index.php">Back</a>
        </div>
    </div>                
</div>
</body>
</html>

Above section contains PHP code on top is used to get id of record from query string and pass that id to database and get users information. If id not passed in query string then it will be redirected to “index.php” page and if invalid id passed in that case it will again redirect to “index.php” page.

Passing a valid id to the read page it will fetch data in $data variable and put it in 2nd part of the page which is HTML and make it view able to you.

PHP CRUD Read page

Create Update page

Create a PHP page for update data “update.php”. This is the update part of CRUD system, as we have already created Create file we use the same file to build form and use PHP of Read form to get data on based of id and make update query.

<?php
    $id = null;
    if(!empty($_GET['id']))
    {
        $id = $_GET['id'];
    }
    if($id == null)
    {
        header("Location: index.php");
    } 
    if ( !empty($_POST))
    {
        require 'db.php';
        // validation errors
        $fnameError     = null;
        $lnameError     = null;
        $ageError       = null;
        $genderError    = null;
        
        // post values
        $fname  = $_POST['fname'];
        $lname  = $_POST['lname'];
        $age    = $_POST['age'];
        $gender = $_POST['gender'];
        
        // validate input
        $valid = true;
        if(empty($fname)) {
            $fnameError = 'Please enter First Name';
            $valid = false;
        }
        
        if(empty($lname)) {
            $lnameError = 'Please enter Last Name';
            $valid = false;
        }
        
        if(empty($age)) {
            $ageError = 'Please enter Age';
            $valid = false;
        }
        
        if(empty($gender)) {
            $genderError = 'Please select Gender';
            $valid = false;
        }
        
        // insert data
        if ($valid) {
            $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "Update users set fname=?,lname=?,age=?,gender=? where id=?";
            $stmt = $PDO->prepare($sql);
            $stmt->execute(array($fname,$lname,$age,$gender,$id));
            $PDO = null;
            header("Location: index.php");
        }
    }
    else{
        require 'db.php';
        $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM users where id = ?";
        $stmt = $PDO->prepare($sql);
        $stmt->execute(array($id));
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        $PDO = null;
        if (empty($data)){
            header("Location: index.php");
        }
        $fname  = $data['FName'];
        $lname  = $data['LName'];
        $age    = $data['Age'];
        $gender = $data['Gender'];
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>
 
<body>
<div class="container">
    
                    <div class="row">
                    <div class="row">
                        <h3>Update a User</h3>
                    </div>
            
                    <form method="POST" action="update.php?id=<?php echo $id?>">
    <div class="form-group <?php echo !empty($fnameError)?'has-error':'';?>">
        <label for="inputFName">First Name</label>
        <input type="text" class="form-control" required="required" id="inputFName" value="<?php echo !empty($fname)?$fname:'';?>" name="fname" placeholder="First Name">
        <span class="help-block"><?php echo $fnameError;?></span>
    </div>
    <div class="form-group <?php echo !empty($lnameError)?'has-error':'';?>">
        <label for="inputLName">Last Name</label>
        <input type="text" class="form-control" required="required" id="inputLName" value="<?php echo !empty($lname)?$lname:'';?>" name="lname" placeholder="Last Name">
        <span class="help-block"><?php echo $lnameError;?></span>
    </div>
    <div class="form-group <?php echo !empty($ageError)?'has-error':'';?>">
        <label for="inputAge">Age</label>
        <input type="number" required="required" class="form-control" id="inputAge" value="<?php echo !empty($age)?$age:'';?>" name="age" placeholder="Age">
        <span class="help-block"><?php echo $ageError;?></span>
    </div>
    <div class="form-group <?php echo !empty($genderError)?'has-error':'';?>">
        <label for="inputGender">Gender</label>
        <select class="form-control" required="required" id="inputGender" name="gender" >
        <option></option>
        <option value="male" <?php echo $gender == 'male'?'selected':'';?>>Male</option>
        <option value="female" <?php echo $gender == 'female'?'selected':'';?>>Female</option>
        </select>
    <span class="help-block"><?php echo $genderError;?></span>
        
    </div>
    
    <div class="form-actions">
        <button type="submit" class="btn btn-primary">Update</button>
        <a class="btn btn btn-default" href="index.php">Back</a>
    </div>
</form>
                
    </div> <!-- /row -->
    </div> <!-- /container -->
</body>
</html>

This code is used to Update a user’s data and its a combined page of Create and Read with the change in query like in create page we used to insert data and here in update page that same query changed to update. Read code of PHP is used to fetch data from table and put in form input fields.

When you post data it will validate data in PHP if data validated successfully the run update query and update your data.

PHP CRUD Update page

Now we have to do final step of PHP CRUD.

Delete Page

Create a page to delete data to do that we have created a file “delete.php” in that file we put below code in our file and add a button in out main page for delete.

<?php
    $id = null;
    if(!empty($_GET['id']))
    {
        $id = $_GET['id'];
    }
    if($id == null)
    {
        header("Location: index.php");
    } 
    if ( !empty($_POST))
    {
        require 'db.php';
        // Delete Data
        $id = $_POST['id'];
        $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "Delete from users where id=?";
        $stmt = $PDO->prepare($sql);
        $stmt->execute(array($id));
        $PDO = null;
        header("Location: index.php");
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>
 
<body>
<div class="container">
    <div class="row">
        <div class="row">
            <h3>Delete a User</h3>
        </div>
    <form method="POST" action="delete.php">
        <input type="hidden" name="id" value="<?php echo $id;?>" />
        <p class="bg-danger" style="padding: 10px;">Are you sure to delete ?</p>
        <div class="form-actions">
            <button type="submit" class="btn btn-danger">Yes</button>
            <a class="btn btn btn-default" href="index.php">No</a>
        </div>
    </form>
                
    </div> <!-- /row -->
    </div> <!-- /container -->
</body>
</html>

The delete page code first of all comes to “delete.php” page and confirm that you want to delete that record with an id in query string. If id not passed in query string then it will be redirected to “index.php” page if id exists it will ask for confirmation with yes and no buttons if you press yes it will delete record and redirect to “index.php” page if you press no it will redirect to “index.php” page without deleting the record.

PHP CRUD Delete page

Finally our PHP CRUD grid looks like this:

PHP CRUD Main page complete

[wpdm_file id=105]DEMO

That’s all for PHP CRUD I hope you enjoyed this tutorial and find it helpful. If you have any question or suggestion please feel free  to comment below. Do share this with your using below social buttons.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

11 responses to “PHP CRUD with Twitter Bootstrap 3 Part – 2/2”

  1. ashington says:

    This is a really nice code, its easier to understand and use

  2. Rahul Sati says:

    good post. code is easy to understand

  3. sak chai says:

    good post. if can use pagination and searching. it very goood

  4. Afdoal Wahyurrahman says:

    how show delete confirm in modal window?? (not in other page)

    thanks b4

  5. Jatin Gupta says:

    Its really good
    i suggest make it – SEO friendly
    Add Custom SLUG/META TAGS field https://www.phpgang.com/how-to-rewrite-urls-with-htaccess_477.html

    Please guide me http://localhost/php-curd/read.php?id=1 to http://localhost/php-curd/huzoor
    If possible please update PART-3 with these updates also add CURD AJAX without refresh content saved/delete/create

  6. pawan parajapat says:

    Huzoor Bux is Great Author for web development coding.

    this script you post that very helpful for me
    thank you Huzoor Bux

  7. adminawala says:

    how to add search function mr huzoor bux ?

  8. Vip3r011 says:

    thanx

  9. Thank you very much for this nice tutorial. I have download script and test all action (create, read, update, delete), it work fine without any error.

Leave a Reply

Your email address will not be published. Required fields are marked *