0% found this document useful (0 votes)
179 views

CRUD With PHP

This document provides the source code for performing CRUD (create, read, update, delete) operations on a MySQL database using PHP and jQuery/Ajax. It includes JavaScript functions for adding, reading, updating, and deleting records from the database. The functions make Ajax calls to PHP files that handle the SQL queries. Modal popups are used for forms to add/update records. On page load, it reads records from the database and displays them.

Uploaded by

ShanmukhaTeli
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
179 views

CRUD With PHP

This document provides the source code for performing CRUD (create, read, update, delete) operations on a MySQL database using PHP and jQuery/Ajax. It includes JavaScript functions for adding, reading, updating, and deleting records from the database. The functions make Ajax calls to PHP files that handle the SQL queries. Modal popups are used for forms to add/update records. On page load, it reads records from the database and displays them.

Uploaded by

ShanmukhaTeli
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Complete Source code of script.

js file:

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
});
<!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">×</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">×</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>
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.

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.

1 CREATE TABLE  `test`.`users` (
2 `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
3 `first_name` VARCHAR( 40 ) NOT NULL ,
4 `last_name` VARCHAR( 40 ) NOT NULL ,
5 `email` VARCHAR( 50 ) NOT NULL
6 ) ENGINE = MYISAM ;
Take a note: test.users – where test is the database name and users is a table name.
Users Table Structure
Basic Structure of Index.php:

Create index.php file and include basic files for jQuery and Bootstrap as showing below:

<!DOCTYPE html>
1 <html lang="en">
2 <head>
3 <meta charset="UTF-8">
4 <title>PHP and MySQL CRUD Operations Demo</title>
5  
6 <!-- Bootstrap CSS File -->
7 <link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-
8 dist/css/bootstrap.css" />
9 </head>
10 <body>
11  
12 <!-- Content Section -->
13  
14 <!-- /Content Section -->
15  
16 <!-- Jquery JS file -->
17 <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
18  
19 <!-- Bootstrap JS file -->
20 <script type="text/javascript" src="bootstrap-3.3.5-
21 dist/js/bootstrap.min.js"></script>
22  
23 <!-- Custom JS file -->
24 <script type="text/javascript" src="js/script.js"></script>
25 </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 <!-- Content Section -->


<div class="container">
2
<div class="row">
3
<div class="col-md-12">
4
<h2>PHP and MySQL CRUD Operations</h2>
5
<div class="pull-right">
6
<button class="btn btn-success" data-toggle="modal" data-
7
target="#add_new_record_modal">Add New Record</button>
8
</div>
9
</div>
10
</div>
11
<div class="row">
12
<div class="col-md-12">
13
<h4>Records:</h4>
14
<div class="records_content"></div>
15
</div>
16
</div>
17
</div>
18
<!-- /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 <!-- Bootstrap Modal - To Add New Record -->


2 <!-- Modal -->
3 <div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog"
4 aria-labelledby="myModalLabel">
5 <div class="modal-dialog" role="document">
6 <div class="modal-content">
7 <div class="modal-header">
8 <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
9 aria-hidden="true">×</span></button>
10 <h4 class="modal-title" id="myModalLabel">Add New Record</h4>
11 </div>
12 <div class="modal-body">
13  
14 <div class="form-group">
15 <label for="first_name">First Name</label>
16 <input type="text" id="first_name" placeholder="First Name" class="form-
17 control" />
18 </div>
19  
<div class="form-group">
<label for="last_name">Last Name</label>
<input type="text" id="last_name" placeholder="Last Name" class="form-control" />
20
</div>
21
 
22
<div class="form-group">
23
<label for="email">Email Address</label>
24
<input type="text" id="email" placeholder="Email Address" class="form-control" />
25
</div>
26
 
27
</div>
28
<div class="modal-footer">
29
<button type="button" class="btn btn-default" data-
30
dismiss="modal">Cancel</button>
31
<button type="button" class="btn btn-primary" onclick="addRecord()">Add
32
Record</button>
33
</div>
34
</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:

Add New Record 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:

Handling Add New Records Action:

Let’s create our custom JS file called script.js file under JS folder and add following code:

js/script.js

1 // Add Record
2 function addRecord() {
3     // get values
4     var first_name = $("#first_name").val();
5     var last_name = $("#last_name").val();
6     var email = $("#email").val();
7  
8     // Add record
9     $.post("ajax/addRecord.php", {
10         first_name: first_name,
11         last_name: last_name,
12         email: email
13     }, function (data, status) {
14         // close the popup
15         $("#add_new_record_modal").modal("hide");
16  
17         // read records again
18         readRecords();
19  
20         // clear fields from the popup
21         $("#first_name").val("");
22         $("#last_name").val("");
23         $("#email").val("");
24     });
25 }
26  
27 // READ records
28 function readRecords() {
29     $.get("ajax/readRecords.php", {}, function (data, status) {
30         $(".records_content").html(data);
31     });
32 }
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.

PHP Script to Add New Record into the database:

Create ajax/addRecord.php file and use following code:

<?php
1 if(isset($_POST['first_name']) && isset($_POST['last_name']) &&
2 isset($_POST['email']))
3 {
4 // include Database connection file
5 include("db_connection.php");
6  
7 // get values
8 $first_name = $_POST['first_name'];
9 $last_name = $_POST['last_name'];
10 $email = $_POST['email'];
11  
12 $query = "INSERT INTO users(first_name, last_name, email)
13 VALUES('$first_name', '$last_name', '$email')";
14 if (!$result = mysqli_query($con, $query)) {
15         exit(mysqli_error($con));
16     }
17     echo "1 Record Added!";
18 }
?>
Process: Accept the values from the POST variablea and insert record into the database.

PHP Script to Read existing Records from the Database:

Create ajax/readRecord.php file and use following code:

1 <?php
2 // include Database connection file
3 include("db_connection.php");
4  
// Design initial table header
5 $data = '<table class="table table-bordered table-striped">
6 <tr>
7 <th>No.</th>
8 <th>First Name</th>
9 <th>Last Name</th>
10 <th>Email Address</th>
11 <th>Update</th>
12 <th>Delete</th>
13 </tr>';
14  
15 $query = "SELECT * FROM users";
16  
17 if (!$result = mysqli_query($con, $query)) {
18         exit(mysqli_error($con));
19     }
20  
21     // if query results contains rows then featch those rows
22     if(mysqli_num_rows($result) > 0)
23     {
24      $number = 1;
25      while($row = mysqli_fetch_assoc($result))
26      {
27      $data .= '<tr>
28 <td>'.$number.'</td>
29 <td>'.$row['first_name'].'</td>
30 <td>'.$row['last_name'].'</td>
31 <td>'.$row['email'].'</td>
32 <td>
33 <button onclick="GetUserDetails('.$row['id'].')"
34 class="btn btn-warning">Update</button>
35 </td>
36 <td>
37 <button onclick="DeleteUser('.$row['id'].')"
38 class="btn btn-danger">Delete</button>
39 </td>
40      </tr>';
41      $number++;
42      }
43     }
44     else
45     {
46      // records now found
47      $data .= '<tr><td colspan="6">Records not found!</td></tr>';
48     }
49  
50     $data .= '</table>';
51  
52     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.

PHP to MysqL Database Connection Script:

Create ajax/db_connection.php file.

Note: Make change in the connection file according to your server configuration.  (Host,
Username, Password and Database name)

<?php
1
 
2
// Connection variables
3
$host = "localhost"; // MySQL host name eg. localhost
4
$user = "root"; // MySQL user. eg. root ( if your on localserver)
5
$password = ""; // MySQL user password  (if password is not set for your root user
6
then keep it empty )
7
$database = "test_db"; // MySQL Database name
8
 
9
// Connect to MySQL Database
10
$con = new mysqli($host, $user, $password, $database);
11
 
12
// Check connection
13
if ($con->connect_error) {
14
    die("Connection failed: " . $con->connect_error);
15
}
16
 
17
?>
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 Dummy
Records List
Handling Read Event on Page Load:

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 $(document).ready(function () {
2     // READ recods on page load
3     readRecords(); // calling function
4 });
Are you Good so far?

Handling Delete Action:

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 function DeleteUser(id) {
2     var conf = confirm("Are you sure, do you really want to delete User?");
3     if (conf == true) {
4         $.post("ajax/deleteUser.php", {
5                 id: id
6             },
7             function (data, status) {
8                 // reload Users by using readRecords();
9                 readRecords();
10             }
11         );
12     }
13 }
PHP Script to Delete existing record from the database:

Create ajax/deleteUser.php file and add following code:


1 <?php
2 // check request
3 if(isset($_POST['id']) && isset($_POST['id']) != "")
4 {
5     // include Database connection file
6     include("db_connection.php");
7  
8     // get user id
9     $user_id = $_POST['id'];
10  
11     // delete User
12     $query = "DELETE FROM users WHERE id = '$user_id'";
13     if (!$result = mysqli_query($con, $query)) {
14         exit(mysqli_error($con));
15     }
16 }
17 ?>
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.

<!-- Modal - Update User details -->


2 <div class="modal fade" id="update_user_modal" tabindex="-1" role="dialog" aria-
3 labelledby="myModalLabel">
4     <div class="modal-dialog" role="document">
5         <div class="modal-content">
6             <div class="modal-header">
7                 <button type="button" class="close" data-dismiss="modal" aria-
8 label="Close"><span aria-hidden="true">×</span></button>
9                 <h4 class="modal-title" id="myModalLabel">Update</h4>
10             </div>
11             <div class="modal-body">
12  
13                 <div class="form-group">
14                     <label for="update_first_name">First Name</label>
15                     <input type="text" id="update_first_name" placeholder="First Name"
16 class="form-control"/>
                </div>
 
                <div class="form-group">
                    <label for="update_last_name">Last Name</label>
17
                    <input type="text" id="update_last_name" placeholder="Last Name"
18
class="form-control"/>
19
                </div>
20
 
21
                <div class="form-group">
22
                    <label for="update_email">Email Address</label>
23
                    <input type="text" id="update_email" placeholder="Email Address"
24
class="form-control"/>
25
                </div>
26
 
27
            </div>
28
            <div class="modal-footer">
29
                <button type="button" class="btn btn-default" data-
30
dismiss="modal">Cancel</button>
31
                <button type="button" class="btn btn-primary"
32
onclick="UpdateUserDetails()" >Save Changes</button>
33
                <input type="hidden" id="hidden_user_id">
34
            </div>
35
        </div>
    </div>
</div>
<!-- // Modal -->
Handling Existing User Details API:

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 function GetUserDetails(id) {
2     // Add User ID to the hidden field for furture usage
3     $("#hidden_user_id").val(id);
4     $.post("ajax/readUserDetails.php", {
5             id: id
6         },
7         function (data, status) {
8             // PARSE json data
9             var user = JSON.parse(data);
10             // Assing existing values to the modal popup fields
11             $("#update_first_name").val(user.first_name);
12             $("#update_last_name").val(user.last_name);
13             $("#update_email").val(user.email);
14         }
15     );
16     // Open modal popup
17     $("#update_user_modal").modal("show");
18 }
PHP Script to Fetch existing user details from the database:

Create ajax/readUserDetails.php file:

1 <?php
2 // include Database connection file
3 include("db_connection.php");
4  
5 // check request
6 if(isset($_POST['id']) && isset($_POST['id']) != "")
7 {
8     // get User ID
9     $user_id = $_POST['id'];
10  
11     // Get User Details
12     $query = "SELECT * FROM users WHERE id = '$user_id'";
13     if (!$result = mysqli_query($con, $query)) {
14         exit(mysqli_error($con));
15     }
16     $response = array();
17     if(mysqli_num_rows($result) > 0) {
18         while ($row = mysqli_fetch_assoc($result)) {
19             $response = $row;
20         }
21     }
22     else
23     {
24         $response['status'] = 200;
25         $response['message'] = "Data not found!";
26     }
27     // display JSON data
28     echo json_encode($response);
29 }
30 else
31 {
32     $response['status'] = 200;
33     $response['message'] = "Invalid Request!";
34 }
Update Action:

Add another JS function called UpdateUserDetails() in to the script.js file:

1 function UpdateUserDetails() {
2     // get values
3     var first_name = $("#update_first_name").val();
4     var last_name = $("#update_last_name").val();
5     var email = $("#update_email").val();
6  
7     // get hidden field value
8     var id = $("#hidden_user_id").val();
9  
10     // Update the details by requesting to the server using ajax
11     $.post("ajax/updateUserDetails.php", {
12             id: id,
13             first_name: first_name,
14             last_name: last_name,
15             email: email
16         },
17         function (data, status) {
18             // hide modal popup
19             $("#update_user_modal").modal("hide");
20             // reload Users by using readRecords();
21             readRecords();
22         }
23     );
24 }
PHP Script to Update Existing Record:

Create ajax/updateUserDetails.php file:

<?php
1 // include Database connection file
2 include("db_connection.php");
3  
4 // check request
5 if(isset($_POST))
6 {
7     // get values
8     $id = $_POST['id'];
9     $first_name = $_POST['first_name'];
10     $last_name = $_POST['last_name'];
11     $email = $_POST['email'];
12  
13     // Updaste User details
14     $query = "UPDATE users SET first_name = '$first_name', last_name = '$last_name',
15 email = '$email' WHERE id = '$id'";
16     if (!$result = mysqli_query($con, $query)) {
17         exit(mysqli_error($con));
18     }
19 }

Folder Structure:

You might also like