Tutorial Lancer

Popular Posts

  • How to use Eloquent ORM without Laravel Framework
    Setup Eloquent ORM with Core PHP Application Laravel framework became a number one framework in php development it has lot of advantages....
  • Medoo php framework
    Lightweight 20KB around with only one file. Easy Extremely easy to learn and use, friendly construction. Powerful Support vario...
  • CRUD Operations in PHP with PDO using Bootstrap
    I have been getting requested to post crud tutorial with PDO connection, so finally it’s here. Tutorial Features: Create, Read, Update...
  • PHP MySQL CRUD (Create, Read, Update, Delete) Operations using jQuery
    PHP MYSQL CRUD PHP MySQL CRUD is all about INSERT, UPDATE, DELETE and SELECT SQL queries using PHP , it will help beginners to know abou...
  • User Account activation by email verification using PHP
    User Account activation, email verification using PHP, MySQL and Swiftmailer Introduction: I have posted tutorials on login registratio...
  • How to Login Multi-Level User using PHP MySQLi and Bootstrap
      In this tutorial I will discuss how to create a login multi-level user by using php mysqli and bootstrap. As usual, create a new folder wi...
  • 100 Best Tools for Coders & Developers
    Want fame and fortune? Learn to code! This post explores the best startups, gadgets, apps, websites and services in a given category. In...
  • Php Templating
    Templates provide a convenient way of separating your controller and domain logic from your presentation logic. Templates typically contain ...
  • How To Become A Super Affiliate In Niche Markets
      Over the past years, web hosting has grown bigger than it used to be. With more companies getting into this business and finding the many ...
  • Which Affiliate Networks To Look Out For When Promoting
      There are many horror stories about affiliate programs and networks. People have heard them over and over again, that some are even wary o...

Labels

  • Affiliate marketing
  • Ajax
  • Angularjs
  • Article Marketing
  • Blogging
  • Click Bank
  • CodeIgniter
  • Development spot
  • Django
  • Free Udemy Course
  • Freebies
  • Github
  • Give Away
  • Ionic
  • Laravel
  • Marketing
  • Phalcon
  • Photoshop tips
  • Php
  • Php 7
  • php frameworks
  • Php mysqli
  • Php pdo
  • Plr Package
  • Plrs
  • Software
  • Tutorials
  • Web Development
Powered by Blogger.
Tutorial Lancer

About Me

Unknown
View my complete profile

How to use Eloquent ORM without Laravel Framework

19:57   Tutorials,

Setup Eloquent ORM with Core PHP Application

Laravel framework became a number one framework in php development it has lot of advantages.
  • Easy to run with homestead.
  • Security
  • Flexibility,
  • documentation
  • Real time support
Apart from the above features Laravel comes up with Eloquent ORM Powerful Database component, it  is used to handle all database related operations.
If you already using laravel framework with your project then it’s good you can skip this post, but if you have a existing application, which is already in development phase and you won’t be able to convert it to laravel because of time limitations and still you wish to use Eloquent ORM  for your future task from the project then this post is going to help you to install eloquent and use.
Before following this tutorial you needs to have composer installed on your system which is going to help to pull in eloquent package.

Step 1: Installing Illuminate Database Component

Create project directory called demo,  if you are installing in existing application then just cd in to you project directory with the terminal.
1
2
mkdir demo
cd demo
Pull Illuminate Database component using composer:
1
composer require illuminate/database
It will create composer.json file (if not exist) in your root directory with require dependancy, it is going to create vendor folder with the required files and folders in it, don’t worry about it for now.
1
2
3
4
5
6
7
8
9
10
Using version ^5.2 for illuminate/database
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing symfony/polyfill-mbstring (v1.2.0)
    Loading from cache
.....
 
Writing lock file
Generating autoload files
Make sure you get above message.
if you open composer.json file it would look like this, version number may change according to the availability.
1
2
3
4
5
{
    "require": {
        "illuminate/database": "^5.2"
    }
}

Step 2: Setup autoload using classmap:

Setting up the autoload is important to have our namespace working, we are going to use here classmap, you can also you psr-4 which is also good option.
Open up the composer.json file and following additional lines next to require:
1
2
3
4
5
6
7
8
9
10
{
    "require": {
        "illuminate/database": "^5.2"
    },
    "autoload":{
        "classmap": [
            "Models"
        ]
    }
}
You might thinking, what we are doing by adding autoload and classmap to the json file?
We basically referencing the Model directory to autoload, after adding those lines use following command to dump and autoload your composer.
1
composer dump-autoload -o

Step 3: Database connection with Eloquent ORM:

Eloquent ORM currently supports MySQL, Postgres, SQL Server, and SQLite, we can easily setup connection with any of those, I am going to use MySQL here for the demo.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
 
use Illuminate\Database\Capsule\Manager as Capsule;
 
$capsule = new Capsule();
 
$capsule->addConnection([
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'orm_test',
    'username'  => 'homestead',
    'password'  => 'secret',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'strict'    => false,
]);
 
$capsule->setAsGlobal();
 
$capsule->bootEloquent();

Step 4: Creating Eloquent ORM Model:

Let’s create our first Eloquent Model, create new directory called Models, here we will store our ORM models.
Add new  Task.php file within the Models folder and use following code:
1
2
3
4
5
6
7
8
<?php
 
use Illuminate\Database\Eloquent\Model as Eloquent;
 
class Task extends Eloquent
{
    
}
We can use all available options ‘$table’, ‘$primaryKey’ or mass assignment array called $fillable and many more.
Before going to use this model, we need database table, to do than we will use Capsule::schema().
Create new file called createTaskTable.php use following code to create new schema for the table:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
use Illuminate\Database\Capsule\Manager as Capsule;
 
// load composer autoload
require __DIR__ .'/vendor/autoload.php';
 
// boot database
require __DIR__ . '/database.php';
 
// create table
Capsule::schema()->create('tasks', function ($table) {
    $table->increments('id');
    $table->string('title');
    $table->string('body');
    $table->timestamps();
});
 
echo 'Table created successfully!';
It is exactly like database migration in Laravel, try to run this file using terminal or with browser:
To run using terminal type in following command:
1
php createTaskTable.php
It should show success message.

Step 5: Using Eloquent ORM Model:

Before going to use our Task Model we have to update it for mass assignment variable, let’s do that now open the file and update it as showing below:
1
2
3
4
5
6
7
8
9
10
11
<?php
 
use Illuminate\Database\Eloquent\Model as Eloquent;
 
class Task extends Eloquent
{
    protected  $fillable = [
        'title',
        'body'
    ];
}
Add testModel.php file to access our Task model and do some operations:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
 
// load composer autoload
require __DIR__ .'/vendor/autoload.php';
 
// boot database
require __DIR__ . '/database.php';
 
// create new task
Task::create([
    'title' => 'Task 1',
    'body' => 'Lorem ipsum'
]);
 
// get all the records from the table
dd(Task::all()->toArray());
Use following command to run file:
1
php testModel.php
it should show following output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
array(1) {
  [0]=>
  array(5) {
    ["id"]=>
    int(1)
    ["title"]=>
    string(6) "Task 1"
    ["body"]=>
    string(11) "Lorem ipsum"
    ["created_at"]=>
    string(19) "2016-07-22 08:56:56"
    ["updated_at"]=>
    string(19) "2016-07-22 08:56:56"
  }
}
If you see new record is created and listed that means your good to go and use Laravel Eloquent ORM  in your project.
Folder Structure:
demo project folder structure
Continue Reading

PHP MySQL CRUD (Create, Read, Update, Delete) Operations using jQuery

19:45  

PHP MYSQL CRUD

PHP MySQL CRUD is all about INSERT, UPDATE, DELETE and SELECT SQL queries using PHP , it will help beginners to know about PHP and MySQL operations.
Note: Don’t use this script into your live projects, the motive of the script is to just provide basic ideas to the beginners for learning, if you want to use this feature in the live projects then you should focus on following points:
  • Prevent your script from SQL Injections
  • Use PDO extension or other DBAL/ORM’s like Laravel Eloquent or Doctrine.

Tutorial Features:

  1. Insert records into MySQL Database
  2. Read the records from Database and list
  3. Update the record
  4. Delete the record.

Technologies Used:

  1. HTML
  2. PHP with MySQL
  3. jQuery
  4. Bootstrap
  5. CSS
  6. JSON
Before starting let’s download basic lib files needed : ( if you already having  this lib files you can use your existing files )
  • Download jQuery JS file from – http://jquery.com/download/
  • Download Bootstrap from – http://getbootstrap.com/getting-started/#download ( Use basic Compiled and minified files don’t go for Source code for now)
Let’s start of creating our demo web application to learn CRUD operations, first thing we are going see is to create a database and tables required. ( if you have your database ready in mysql go ahead and create tables using following sql code) I am assuming that you have database created and ready to use.
users table
1
2
3
4
5
6
CREATE TABLE  `test`.`users` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`first_name` VARCHAR( 40 ) NOT NULL ,
`last_name` VARCHAR( 40 ) NOT NULL ,
`email` VARCHAR( 50 ) NOT NULL
) ENGINE = MYISAM ;
Take a note: test.users – where test is the database name and users is a table name.
IMAGE : Users Table Structure
Users Table Structure
Create index.php file and include basic files for jQuery and Bootstrap as showing below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP and MySQL CRUD Operations Demo</title>
 
<!-- Bootstrap CSS File -->
<link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-dist/css/bootstrap.css" />
</head>
<body>
 
<!-- Content Section -->
 
<!-- /Content Section -->
 
<!-- Jquery JS file -->
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
 
<!-- Bootstrap JS file -->
<script type="text/javascript" src="bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
 
<!-- Custom JS file -->
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
So we have our basic file ready to go, now let’s add button to open add new record popup along with basic formatting like to have page heading and record container, refer following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- Content Section -->
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>PHP and MySQL CRUD Operations</h2>
<div class="pull-right">
<button class="btn btn-success" data-toggle="modal" data-target="#add_new_record_modal">Add New Record</button>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h4>Records:</h4>
<div class="records_content"></div>
</div>
</div>
</div>
<!-- /Content Section -->
The above code is actually part of our index.php file, if you look at it, you will notice we have application heading and Add New Record button which refers to add_new_record_modal modal popup. we also have records_content div, this div is going to display the data rendering from Ajax, we are going to see that next.
Now we need to add modal popup, we are using bootstrap modal popups here, go a head and use following code to include popup in the index.php page.
If you’re not familiar with Bootstrap no worries you just need to copy this code later on you can read about it, so now go ahead and add below modal to you index.php page.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!-- Bootstrap Modal - To Add New Record -->
<!-- Modal -->
<div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">Add New Record</h4>
</div>
<div class="modal-body">
 
<div class="form-group">
<label for="first_name">First Name</label>
<input type="text" id="first_name" placeholder="First Name" class="form-control" />
</div>
 
<div class="form-group">
<label for="last_name">Last Name</label>
<input type="text" id="last_name" placeholder="Last Name" class="form-control" />
</div>
 
<div class="form-group">
<label for="email">Email Address</label>
<input type="text" id="email" placeholder="Email Address" class="form-control" />
</div>
 
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="addRecord()">Add Record</button>
</div>
</div>
</div>
</div>
If you notice in the above code we have popup called add_new_record_modal which includes different input field in the ‘modal-body’ tag. so we have first name, last name and email address here.
modal-footer – that’s the important part of the popup to call action such as addRecord, we have button with JS method call with onclick event.
let’s save index.page page and try to load on browser.
Index.php Page:
crud-basic-screen
Add New Record Popup:
Add New Record Modal Popup

Next Step is to create Add New Record and Read Records feature.
We have seen the basic setup of our application now we are going to look at the CREATE and READ operation. That is also called as INSERT and SELECT operation in MySQL, basically to create new record in the table.
It’s time to code jQuery plus JavaScript:
Let’s create our custom JS file called script.js file under JS folder and add following code:
js/script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Add Record
function addRecord() {
    // get values
    var first_name = $("#first_name").val();
    var last_name = $("#last_name").val();
    var email = $("#email").val();
 
    // Add record
    $.post("ajax/addRecord.php", {
        first_name: first_name,
        last_name: last_name,
        email: email
    }, function (data, status) {
        // close the popup
        $("#add_new_record_modal").modal("hide");
 
        // read records again
        readRecords();
 
        // clear fields from the popup
        $("#first_name").val("");
        $("#last_name").val("");
        $("#email").val("");
    });
}
 
// READ records
function readRecords() {
    $.get("ajax/readRecords.php", {}, function (data, status) {
        $(".records_content").html(data);
    });
}
If you notice in the above code, we have addRecord() function which is doing following operation: Get the Values from the input fields and send it to addRecord.php file using Ajax call. After that it’s closing the popup and reading records using readRecords() that is next function to it.
Create ajax/addRecord.php file and use following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
    if(isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email']))
    {
        // include Database connection file
        include("db_connection.php");
 
        // get values
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $email = $_POST['email'];
 
        $query = "INSERT INTO users(first_name, last_name, email) VALUES('$first_name', '$last_name', '$email')";
        if (!$result = mysqli_query($con, $query)) {
            exit(mysqli_error($con));
        }
        echo "1 Record Added!";
    }
?>
Process: Accept the values from the POST variablea and insert record into the database.
Create ajax/readRecord.php file and use following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
    // include Database connection file
    include("db_connection.php");
 
    // Design initial table header
    $data = '<table class="table table-bordered table-striped">
                        <tr>
                            <th>No.</th>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Email Address</th>
                            <th>Update</th>
                            <th>Delete</th>
                        </tr>';
 
    $query = "SELECT * FROM users";
 
    if (!$result = mysqli_query($con, $query)) {
        exit(mysqli_error($con));
    }
 
    // if query results contains rows then featch those rows
    if(mysqli_num_rows($result) > 0)
    {
        $number = 1;
        while($row = mysqli_fetch_assoc($result))
        {
            $data .= '<tr>
                <td>'.$number.'</td>
                <td>'.$row['first_name'].'</td>
                <td>'.$row['last_name'].'</td>
                <td>'.$row['email'].'</td>
                <td>
                    <button onclick="GetUserDetails('.$row['id'].')" class="btn btn-warning">Update</button>
                </td>
                <td>
                    <button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
                </td>
            </tr>';
            $number++;
        }
    }
    else
    {
        // records now found
        $data .= '<tr><td colspan="6">Records not found!</td></tr>';
    }
 
    $data .= '</table>';
 
    echo $data;
?>
In both files above I have included the db_connection.php file using php include() function, this files is use to define our database connection string. It is better practice to add repetitive code in the separate file, let’s create the file.
Create ajax/db_connection.php file.
Note: Make change in the connection file according to your server configuration.  (Host, Username, Password and Database name)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
 
// Connection variables
$host = "localhost"; // MySQL host name eg. localhost
$user = "root"; // MySQL user. eg. root ( if your on localserver)
$password = ""; // MySQL user password  (if password is not set for your root user then keep it empty )
$database = "test_db"; // MySQL Database name
 
// Connect to MySQL Database
$con = new mysqli($host, $user, $password, $database);
 
// Check connection
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}
 
?>
Test the application: try to add new record, you will need to be able to add the record and have it listed, have a look on below screen shoot I have added few dummy records:
Fill the fields and click on Add Record button:
Add New Test Record
Add New Test Record
Dummy Records List
Dummy Records List

Whenever we load the page we needs to have our existing records to be list on the page right? So go ahead ad added following code in to the script.js file and try to page again.
1
2
3
4
$(document).ready(function () {
    // READ recods on page load
    readRecords(); // calling function
});
Are you Good so far?
So now have we have our CREATE and READ feature is ready and tested, let’s go to next step and add DELETE and UPDATE feature as well.
Add DeleteUser() function in the custom scrip.js file:
1
2
3
4
5
6
7
8
9
10
11
12
13
function DeleteUser(id) {
    var conf = confirm("Are you sure, do you really want to delete User?");
    if (conf == true) {
        $.post("ajax/deleteUser.php", {
                id: id
            },
            function (data, status) {
                // reload Users by using readRecords();
                readRecords();
            }
        );
    }
}
Create ajax/deleteUser.php file and add following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
    // include Database connection file
    include("db_connection.php");
 
    // get user id
    $user_id = $_POST['id'];
 
    // delete User
    $query = "DELETE FROM users WHERE id = '$user_id'";
    if (!$result = mysqli_query($con, $query)) {
        exit(mysqli_error($con));
    }
}
?>

UPDATE Feature

How does it work?
Let me explain in the step:
  1. User clicks on update button from the list
  2. Popup open up with the existing details field in
  3. User can click on Save Changes button to update and save the records.
Get back to the code, so add required modal popup to update the record.
Go ahead and use the following html code and add to the index.php page, next to the existing modal popup.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!-- Modal - Update User details -->
<div class="modal fade" id="update_user_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Update</h4>
            </div>
            <div class="modal-body">
 
                <div class="form-group">
                    <label for="update_first_name">First Name</label>
                    <input type="text" id="update_first_name" placeholder="First Name" class="form-control"/>
                </div>
 
                <div class="form-group">
                    <label for="update_last_name">Last Name</label>
                    <input type="text" id="update_last_name" placeholder="Last Name" class="form-control"/>
                </div>
 
                <div class="form-group">
                    <label for="update_email">Email Address</label>
                    <input type="text" id="update_email" placeholder="Email Address" class="form-control"/>
                </div>
 
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="UpdateUserDetails()" >Save Changes</button>
                <input type="hidden" id="hidden_user_id">
            </div>
        </div>
    </div>
</div>
<!-- // Modal -->
Add getUserDetails() function in to the script.js file:
This function is used to read the existing user details and fill input fields from modal popup and open it up.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function GetUserDetails(id) {
    // Add User ID to the hidden field for furture usage
    $("#hidden_user_id").val(id);
    $.post("ajax/readUserDetails.php", {
            id: id
        },
        function (data, status) {
            // PARSE json data
            var user = JSON.parse(data);
            // Assing existing values to the modal popup fields
            $("#update_first_name").val(user.first_name);
            $("#update_last_name").val(user.last_name);
            $("#update_email").val(user.email);
        }
    );
    // Open modal popup
    $("#update_user_modal").modal("show");
}
Create ajax/readUserDetails.php file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
// include Database connection file
include("db_connection.php");
 
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
    // get User ID
    $user_id = $_POST['id'];
 
    // Get User Details
    $query = "SELECT * FROM users WHERE id = '$user_id'";
    if (!$result = mysqli_query($con, $query)) {
        exit(mysqli_error($con));
    }
    $response = array();
    if(mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $response = $row;
        }
    }
    else
    {
        $response['status'] = 200;
        $response['message'] = "Data not found!";
    }
    // display JSON data
    echo json_encode($response);
}
else
{
    $response['status'] = 200;
    $response['message'] = "Invalid Request!";
}
Add another JS function called UpdateUserDetails() in to the script.js file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function UpdateUserDetails() {
    // get values
    var first_name = $("#update_first_name").val();
    var last_name = $("#update_last_name").val();
    var email = $("#update_email").val();
 
    // get hidden field value
    var id = $("#hidden_user_id").val();
 
    // Update the details by requesting to the server using ajax
    $.post("ajax/updateUserDetails.php", {
            id: id,
            first_name: first_name,
            last_name: last_name,
            email: email
        },
        function (data, status) {
            // hide modal popup
            $("#update_user_modal").modal("hide");
            // reload Users by using readRecords();
            readRecords();
        }
    );
}
Create ajax/updateUserDetails.php file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
// include Database connection file
include("db_connection.php");
 
// check request
if(isset($_POST))
{
    // get values
    $id = $_POST['id'];
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $email = $_POST['email'];
 
    // Updaste User details
    $query = "UPDATE users SET first_name = '$first_name', last_name = '$last_name', email = '$email' WHERE id = '$id'";
    if (!$result = mysqli_query($con, $query)) {
        exit(mysqli_error($con));
    }
}
Folder Structure:
Folder Structure
Folder Structure
Complete Source code of script.js file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Add Record
function addRecord() {
    // get values
    var first_name = $("#first_name").val();
    var last_name = $("#last_name").val();
    var email = $("#email").val();
 
    // Add record
    $.post("ajax/addRecord.php", {
        first_name: first_name,
        last_name: last_name,
        email: email
    }, function (data, status) {
        // close the popup
        $("#add_new_record_modal").modal("hide");
 
        // read records again
        readRecords();
 
        // clear fields from the popup
        $("#first_name").val("");
        $("#last_name").val("");
        $("#email").val("");
    });
}
 
// READ records
function readRecords() {
    $.get("ajax/readRecords.php", {}, function (data, status) {
        $(".records_content").html(data);
    });
}
 
 
function DeleteUser(id) {
    var conf = confirm("Are you sure, do you really want to delete User?");
    if (conf == true) {
        $.post("ajax/deleteUser.php", {
                id: id
            },
            function (data, status) {
                // reload Users by using readRecords();
                readRecords();
            }
        );
    }
}
 
function GetUserDetails(id) {
    // Add User ID to the hidden field for furture usage
    $("#hidden_user_id").val(id);
    $.post("ajax/readUserDetails.php", {
            id: id
        },
        function (data, status) {
            // PARSE json data
            var user = JSON.parse(data);
            // Assing existing values to the modal popup fields
            $("#update_first_name").val(user.first_name);
            $("#update_last_name").val(user.last_name);
            $("#update_email").val(user.email);
        }
    );
    // Open modal popup
    $("#update_user_modal").modal("show");
}
 
function UpdateUserDetails() {
    // get values
    var first_name = $("#update_first_name").val();
    var last_name = $("#update_last_name").val();
    var email = $("#update_email").val();
 
    // get hidden field value
    var id = $("#hidden_user_id").val();
 
    // Update the details by requesting to the server using ajax
    $.post("ajax/updateUserDetails.php", {
            id: id,
            first_name: first_name,
            last_name: last_name,
            email: email
        },
        function (data, status) {
            // hide modal popup
            $("#update_user_modal").modal("hide");
            // reload Users by using readRecords();
            readRecords();
        }
    );
}
 
$(document).ready(function () {
    // READ recods on page load
    readRecords(); // calling function
});
Complete Source code of index.php file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP and MySQL CRUD Operations Demo</title>
 
    <!-- Bootstrap CSS File  -->
    <link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-dist/css/bootstrap.css"/>
</head>
<body>
 
<!-- Content Section -->
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1>Demo: PHP and MySQL CRUD Operations using Jquery</h1>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="pull-right">
                <button class="btn btn-success" data-toggle="modal" data-target="#add_new_record_modal">Add New Record</button>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <h3>Records:</h3>
 
            <div class="records_content"></div>
        </div>
    </div>
</div>
<!-- /Content Section -->
 
 
<!-- Bootstrap Modals -->
<!-- Modal - Add New Record/User -->
<div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Add New Record</h4>
            </div>
            <div class="modal-body">
 
                <div class="form-group">
                    <label for="first_name">First Name</label>
                    <input type="text" id="first_name" placeholder="First Name" class="form-control"/>
                </div>
 
                <div class="form-group">
                    <label for="last_name">Last Name</label>
                    <input type="text" id="last_name" placeholder="Last Name" class="form-control"/>
                </div>
 
                <div class="form-group">
                    <label for="email">Email Address</label>
                    <input type="text" id="email" placeholder="Email Address" class="form-control"/>
                </div>
 
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="addRecord()">Add Record</button>
            </div>
        </div>
    </div>
</div>
<!-- // Modal -->
 
<!-- Modal - Update User details -->
<div class="modal fade" id="update_user_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Update</h4>
            </div>
            <div class="modal-body">
 
                <div class="form-group">
                    <label for="update_first_name">First Name</label>
                    <input type="text" id="update_first_name" placeholder="First Name" class="form-control"/>
                </div>
 
                <div class="form-group">
                    <label for="update_last_name">Last Name</label>
                    <input type="text" id="update_last_name" placeholder="Last Name" class="form-control"/>
                </div>
 
                <div class="form-group">
                    <label for="update_email">Email Address</label>
                    <input type="text" id="update_email" placeholder="Email Address" class="form-control"/>
                </div>
 
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="UpdateUserDetails()" >Save Changes</button>
                <input type="hidden" id="hidden_user_id">
            </div>
        </div>
    </div>
</div>
<!-- // Modal -->
 
<!-- Jquery JS file -->
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
 
<!-- Bootstrap JS file -->
<script type="text/javascript" src="bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
 
<!-- Custom JS file -->
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
Finally we are done with the CREATE, READ, UPDATE and DELETE feature, test it on your system and let me know if you get any issue with the all above code.
Continue Reading
Older Posts Home
Subscribe to: Posts (Atom)
Designed By: Blogger Templates | Templatelib