June 25, 2014 5:12 pm

PHP CRUD with Twitter Bootstrap 3 Part – 1/2

PHP CRUD I have received many requests from my readers to create some article on CRUD (stand for Create/Read/Update/Delete) grid its a very common task in web development and we always implement it in our applications very frequently. The purpose of creating CRUD grid is to give an option to your users to Create/Read/Update/Delete data. Your data stored in database and here we are using MySQL database. To display grid we use bootstrap framework.

PHP CRUD with Twitter Bootstrap Part - 1

Basically we divided this tutorial in 2 parts due to lengthy process.

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

In first part we will cover few steps of PHP CRUD like Create Database, Database Connection, Bootstrap grid, Read Data and Create Data other CRUD operation we will cover in our next tutorial.

Database design and table:

database name => phpgang
table name => users
column names => ID, FName, LName, Age, Gender

db.sql

Database file run in your MySQL to create database and add data in table.

CREATE TABLE users (
    ID int(11) NOT NULL AUTO_INCREMENT,
    FName varchar(50) NOT NULL,
    LName varchar(50) NOT NULL,
    Age int(11) NOT NULL,
    Gender enum('male','female') NOT NULL,
    PRIMARY KEY (ID)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

Database connection:

db.php File contens database credentials to connect with database using PDO:

<?php
    $host      = DB_HOST;
    $user      = DB_USER;
    $pass      = DB_PASS;
    $dbname    = DB_NAME;
    try 
    {
        $PDO =  new PDO( "mysql:host=".$host.";"."dbname=".$dbname, $user, $pass);  
    }
    catch(PDOException $e) 
    {
        die($e->getMessage());  
    }
?>

You have to change database values to access your own database.

$host: Database host normally “localhost”.
$user: Database user have access the database tables and run queries.
$pass: Database password required to protect your database.
$dbname: Database name contains your required table.

Bootstrap Grid

Bootstrap is a famous front-end framework to create responsive and clean user interface you can download it from here and its also included in our tutorial download.

Directory looks like this:


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
index.php
db.php
create.php

Create grid in index.php file with below markup:

<!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">
    <h3>PHP CRUD Grid</h3>
    </div>
    <div class="row">
    <p><a class="btn btn-xs btn-success" href="create.php">Create</a></p>
    <table class="table table-striped table-bordered table-hover">
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
        <th>Action</th>
    </tr>
    <tbody>
    <?php
    include 'db.php';
    $sql = 'SELECT * FROM users ORDER BY ID DESC';
    foreach ($PDO->query($sql) as $row) {
        echo '<tr>';
        echo '<td>'. $row['ID'] . '</td>';
        echo '<td>'. $row['FName'] . ' '. $row['LName'] . '</td>';
        echo '<td>'. $row['Age'] . '</td>';
        echo '<td>'. $row['Gender'] . '</td>';
        echo '<td>&nbsp;</td>';
        echo '</tr>';
    }
$PDO = null;
    ?>
    </tbody>
    </table>
    </div><!-- /row -->
</div><!-- /container -->
</body>
</html>

Above markup is created under bootstrap user interface rules. table table-striped table-bordered table-hover class given to table to define what kind of table we are going to create like table with border highlight row on hand over stripped color.

PHP CRUD Main page

Create Data

Now its time to make a file to create data create.php file in this file we created a form to get data from our users and insert in our database.

<?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 = "INSERT INTO users (fname,lname,age,gender) values(?, ?, ?, ?)";
            $stmt = $PDO->prepare($sql);
            $stmt->execute(array($fname,$lname,$age,$gender));
            $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>Create a User</h3>
                    </div>
            
                    <form method="POST" action="">
    <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-success">Create</button>
        <a class="btn btn-default" href="index.php">Back</a>
    </div>
</form>
                
    </div> <!-- /row -->
    </div> <!-- /container -->
</body>
</html>

In this page you see a form which add data in table user and redirect you to the index page, when some one post data we first of all check validation of posted data we have added client side validation as well but its necessary to validate user data on server side.

PHP CRUD Create page

That’s all for part 1 we will update part 2 very soon I hope this helps you. Complete demo and source code will be available after publishing remaining 2nd part.

Read Part 2 of PHP CRUD

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:

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

  1. Ben Lue says:

    Hmm this tutorial isnt working :/

  2. Dean says:

    i always get the undefined varible fnameError,lnameError, ageError

  3. Mochi Ongpin says:

    always getting this I copy and pasted your code. please help

  4. Mochi Ongpin says:

    sir the “form-group has-error” and the span tag “help-block” that display error messages are not working please help me out. im trying to fix your code. I fixed the undefined variable by putting isset.

  5. Mochi Ongpin says:

    sir please remove the required=”required” if you want the condition for form-group has-error and help-block to work. im working on modifying you codes while im learning 🙂 I also put a name to the submit button and changed the !empty($_POST) to isset($_POST[‘btnSub’])

  6. Mochi Ongpin says:

    got it working like this 🙂

  7. Mounish Moni says:

    Thank you sharing this tutorial. Its working fine..:)

Leave a Reply

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