CRUD With Backbone.JS and PHP MySQL

CRUD With Backbone.JS and PHP MySQL

In this tutorial will discuss how to add data, view data, edit or update data and delete data using backbone.js and php mysql, CRUD operation is an stand for add data, view/read data, edit or update data and delete data. The way it works is almost the same as CRUD in php mysql but here it is emphasized using Backbone.js. The difference is only in the use of the framework only.

Backbone.js is a JavaScript MV * that supports routes, data bindings, and models, just like their rivals such as AngularJS and EmberJS, for AngularJS other articles will be created to discuss it. Backbone.js function is similar to ajax function that is post, get, put and delete but backbone.js has many features like routes and models, besides, backbone.js and ajax can be put together in one file or in the backbone code.

As in this tutorial, combine between backbone.js with ajax, ajax only handle data and update data only while others will be handled by backbone.js. How to create CRUD by using Backbone.JS and PHP MySQL as below.

Create Database

Creating a database for storing data, data will be input through input form and will be executed by backbone.js and php then then saved into the mysql database. For database and table names use the crud or mydata name or like the syntax code below.

CREATE DATABASE IF NOT EXISTS `mydata` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `mydata`;

CREATE TABLE `crud` (
  `id` int(11) NOT NULL PRIMARY KEY,
  `name` varchar(60) NOT NULL,
  `email` varchar(45) NOT NULL,
  `phone` varchar(20) NOT NULL,
  `address` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Basic Backbone

Basic backbone here means is a function that is often used on all backbone applications that are routers and models, below is the router and model syntax code.

Routers.js

"use strict";

window.APP = window.APP || {};
APP.crudRouter = Backbone.Router.extend({
  routes: {
    "crud/new": "create",
    "crud/index": "index",
    "crud/:id/edit": "edit",
    "crud/:id/delete": "delete"
  },

  $container: $('#primary-content'),

  initialize: function () {
    this.collection = new APP.crudCollection();
    this.collection.fetch({ajaxSync: false});
    APP.helpers.debug(this.collection);
    this.index();
    Backbone.history.start();
  },

  create: function () {
    var view = new APP.crudNewView({
      collection: this.collection, 
      model: new APP.crudModel()
    });
    this.$container.html(view.render().el);
    $('.myid').val(_.random(0, 10000));
  },

  delete: function (id) {
    var crud = this.collection.get(id);
    crud.destroy();
    $.get("crud.php?p=trash", { id: id }, function(data){
      Backbone.history.navigate("crud/index", {trigger: true});
    });
  },

  edit: function (id) {
    var view = new APP.crudEditView({model: this.collection.get(id)});
    this.$container.html(view.render().el);
  },

  index: function () {
    var view = new APP.crudIndexView({collection: this.collection});
    this.$container.html(view.render().el);
  }
});

Models.js

"use strict";
APP.crudModel = Backbone.Model.extend({
  defaults: {
    name: "",
    address: "",
    email: "",
    phone: "",
    id: ""
  },

  validate: function (attrs) {
    var errors = {};
    if (!attrs.name) errors.name = "Bèk tuwö nan droëkeuh";
    if (!attrs.address) errors.address = "Teumpat tinggai droëkeuh peu katuwö";
    if (!attrs.email) errors.email = "Surèl droëkeuh kapasoe beh";
    if (!attrs.phone) errors.phone = "Numboi hp kah bèk tuwö";
    if (!_.isEmpty(errors)) return errors;
  }
});

APP.crudCollection = Backbone.Collection.extend({
  model: APP.crudModel,
  url: 'crud.php'
});

Helpers.js

(function () {
  APP.helpers = {

    debug: function (collection) {
      collection.on('all', function () {
        $('#output').text(JSON.stringify(collection.toJSON(), null, 4));
      });
      collection.trigger('reset');
    },

    showErrors: function (note, errors) {
      $('.has-error').removeClass('has-error');
      $('.alert').html(_.values(errors).join('<br>')).show();

      _.each(_.keys(errors), function (key) {
        $('*[name=' + key + ']').parent().addClass('has-error');
      });
    }
  };
}());

Library Framework

Creating a cool layout can use the common framework Bootstrap, Awesome Fonts and others, For libraries like syntax code below.

<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">

<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/backbone/underscore-min.js"></script>
<script src="assets/backbone/backbone-min.js"></script>
<script src="assets/backbone/backbone.localStorage.js"></script>
<script src="routers.js"></script>
<script src="models.js"></script>
<script src="views/view.js"></script>
<script src="views/add.js"></script>
<script src="views/edit.js"></script>
<script src="helpers.js"></script>
<script>
    var app = new APP.crudRouter();
</script>

Layout Design

The layout design here is the display using the html syntax code along with the class that will connect to the framework library like bootstrap.

<div class="container">
        <div class="page-header">
        <h1>CRUD BackboneJS PHP MySQL</h1>
        </div>

        <div class="panel panel-default">
            <div class="panel-body" id="primary-content">
                <!-- this is content -->
            </div>
        </div>
        <button style="margin:10px 0;" class="btn btn-warning" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample"><i class="fa fa-desktop"></i> Show Output JSON</button>
        <div class="collapse" id="collapseExample">
            <code id="output" style="display:block;white-space:pre-wrap;"></code>
        </div>
</div>

<script type="text/jst" id="formTemplate">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <div class="alert alert-danger fade in" style="display:none;"></div>
                <form>
                    <h2><%= name %></h2>
                    <% if(_.isEmpty(id)==false){ %>
                    <div class="form-group">
                        <label>ID:</label>
                        <input type="text" class="form-control" name="id" value="<%= id %>" readonly />
                    </div>
                    <% } else{ %>
                    <div class="form-group">
                        <label>ID:</label>
                        <input type="text" class="form-control myid" name="id"/>
                    </div>
                    <% } %>
                    <div class="form-group">
                        <label>Name:</label>
                        <input type="text" class="form-control" name="name" value="<%= name %>" />
                    </div>
                    <div class="form-group">
                        <label>Email:</label>
                        <input type="text" class="form-control" name="email" value="<%= email %>" />
                    </div>
                    <div class="form-group">
                        <label>Phone:</label>
                        <input type="text" class="form-control" name="phone" value="<%= phone %>" />
                    </div>
                    <div class="form-group">
                        <label>Address:</label>
                        <textarea class="form-control" rows="5" name="address"><%= address %></textarea>
                    </div>
                    <button class="save btn btn-large btn-info" type="submit">Save</button>
                    <a href="#crud/index" class="btn btn-large btn-default">Cancel</a>
                </form>
            </div>
        </div>
</script>

<script type="text/template" id="indexTemplate">

        <a style="margin:10px 0px;" class="btn btn-large btn-info" href="#crud/new"><i class="fa fa-plus"></i> Create New Data</a>
        <a data-toggle="collapse" data-target="#collapseExample2" aria-expanded="false" aria-controls="collapseExample2" style="margin:10px 0px;" class="btn btn-large btn-success" href="#crud/index"><i class="fa fa-list"></i> View Data (Double Click)</a>

        <div class="collapse" id="collapseExample2">
        <% if (_.isEmpty(cruds)){ %>
        <div class="alert alert-warning">
            <p>There are currently no cruds. Try creating some.</p>
        </div>
        <% } %>

        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Address</th>
                    <th width="140">Action</th>
                </tr>
            </thead>
            <tbody>
                <% _.each(cruds, function (crud) { %>
                <tr>
                    <td><%= crud.id %></td>
                    <td><%= crud.name %></td>
                    <td><%= crud.email %></td>
                    <td><%= crud.phone %></td>
                    <td><%= crud.address %></td>
                    <td class="text-center">
                        <a class="btn btn-xs btn-info" href="#crud/<%= crud.id %>/edit"><i class="fa fa-pencil"></i> Edit</a>
                        <a class="btn btn-xs btn-danger" href="#crud/<%= crud.id %>/delete"><i class="fa fa-trash"></i> Delete</a>
                    </td>
                </tr>
                <% }); %>
            </tbody>
        </table>
        </div>

</script>

View Data

View data is to display data from database into html table.

"use strict";
APP.crudIndexView = Backbone.View.extend({
  
  template: _.template($('#indexTemplate').html()),

  render: function () {
    this.$el.html(
    	this.template({cruds: this.collection.toJSON()})
    );
    return this;
  }
});

Add Data

Add data is process added data through input form then will be executed by backbone and php then saved to database.

"use strict";

APP.crudNewView = Backbone.View.extend({
  events: {
    "click button.save": "save",
    "keyup input": "validate",
    "keyup textarea": "validate"
  },
  
  template: _.template($('#formTemplate').html()),

  initialize: function (options) {
    this.model.bind('invalid', APP.helpers.showErrors, APP.helpers);
  },

  save: function (event) {
    event.stopPropagation();
    event.preventDefault();

    this.model.set({
      id: this.$el.find('input[name=id]').val(),
      name: this.$el.find('input[name=name]').val(),
      email: this.$el.find('input[name=email]').val(),
      phone: this.$el.find('input[name=phone]').val(),
      address: this.$el.find('textarea[name=address]').val()
    });
    
    if (this.model.isValid()) {
      this.collection.add(this.model);
      this.model.save();
      var id = this.$el.find('input[name=id]').val();
      var nm = this.$el.find('input[name=name]').val();
      var em = this.$el.find('input[name=email]').val();
      var hp = this.$el.find('input[name=phone]').val();
      var ad = this.$el.find('textarea[name=address]').val();
      $.post("crud.php?p=add", { id: id, name: nm, email: em, phone: hp, address: ad } , function(data){
        Backbone.history.navigate("crud/index", {trigger: true});
      });
    }
  },

  render: function () {
    this.$el.html(
    	this.template(this.model.toJSON())
    );
    return this;
  }
});

Edit Data

Edit or update data is the process change data that starts from reading data into input form by id then data in input form is updated when update button is clicked.

"use strict";
APP.crudEditView = Backbone.View.extend({
  events: {
    "click button.save": "save"
  },

  template: _.template($('#formTemplate').html()),

  initialize: function (options) {
    this.model.bind('invalid', APP.helpers.showErrors, APP.helpers);
    this.model.bind('invalid', this.invalid, this);
  },

  invalid: function () {
    this.$el.find('a.cancel').hide();
  },

  save: function (event) {
    event.stopPropagation();
    event.preventDefault();

    this.model.set({
      id: this.$el.find('input[name=id]').val(),
      name: this.$el.find('input[name=name]').val(),
      email: this.$el.find('input[name=email]').val(),
      phone: this.$el.find('input[name=phone]').val(),
      address: this.$el.find('textarea[name=address]').val()
    });

    if (this.model.isValid()) {
      this.model.save();
      var id = this.$el.find('input[name=id]').val();
      var nm = this.$el.find('input[name=name]').val();
      var em = this.$el.find('input[name=email]').val();
      var hp = this.$el.find('input[name=phone]').val();
      var ad = this.$el.find('textarea[name=address]').val();
      $.post("crud.php?p=edit", { id: id, name: nm, email: em, phone: hp, address: ad } , function(data){
        Backbone.history.navigate("crud/index", {trigger: true});
      });
    }
  },

  render: function () {
    this.$el.html(
      this.template(this.model.toJSON())
    );
    return this;
  }
});
$db = new PDO("mysql:host=localhost;dbname=mydata", "root", "");
$page = isset($_GET['p'])? $_GET['p'] : '';
if($page=='add'){
    $sql = "INSERT INTO crud values (:id,:nm,:em,:hp,:ad)";
    $query = $db->prepare($sql);
    $query->execute(array(":id"=>$_POST['id'],":nm"=>$_POST['name'],":em"=>$_POST['email'],":hp"=>$_POST['phone'],":ad"=>$_POST['address']));
} else if($page=='edit'){
    $sql = "UPDATE crud SET name= :nm, email= :em, phone= :hp, address= :ad WHERE id = :id";
    $query = $db->prepare($sql);
    $query->execute(array(":nm"=>$_POST['name'],":em"=>$_POST['email'],":hp"=>$_POST['phone'],":ad"=>$_POST['address'], ":id"=>$_POST['id']));
} else if($page=='trash'){
    $sql = "DELETE FROM crud WHERE id = :id";
    $query = $db->prepare($sql);
    $query->execute(array(":id"=>$_GET['id']));
} else{
    $statement = $db->query('SELECT * FROM crud');
    $statement->setFetchMode(PDO::FETCH_ASSOC);
    echo json_encode($statement->fetchAll());
}

Thank you for you visit my blog tutorial, hopeful useful, and you can download this source code below.

 

CRUD With Backbone.JS and PHP MySQL

Shopping Cart With PHP and jQuery

Shopping Cart With PHP and jQuery

Online store is now more popular than offline stores, this is caused by people who really want to spend more time at home, easier to shop online effortlessly search for the desired product, just search on searchable columns and meet, different from shopping shop Offline is arguably very difficult to find what we need because out of stores and into other stores just to find one type of product only.

With shopping on the online store can save time because enough at home and purchased products will be sent via a delivery service provided by the online store. Online stores can be accessed as long as our home connected with internet and requires devices such as computers, smartphones, tablets and others.

In this tutorial will be discussed how to create shopping cart by using jquery, ajax, jquery.mycart and php, jquery.mycart.js can be found at github.com/Asraf-Uddin-Ahmed/jquery.mycart. For an explanation of how to create a shopping cart using jquery and php as below.

Creating Database

This database is to store product data, user data and temporary purchase data after checkout. Create a new database with the name of the cart and three tables with the name of each table is, product, shopping, and user or you can use the sql code below

CREATE DATABASE IF NOT EXISTS `cart` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `cart`;

CREATE TABLE `product` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(80) NOT NULL,
  `summary` varchar(255) NOT NULL,
  `price` double NOT NULL,
  `quantity` varchar(10) NOT NULL,
  `image` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `shopping` (
  `id_user` int(2) NOT NULL PRIMARY KEY,
  `id` int(11) NOT NULL PRIMARY KEY,
  `amount_quantity` varchar(10) NOT NULL,
  `amount_price` double NOT NULL,
  `order_number` int(7) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `user` (
  `id_user` int(2) NOT NULL PRIMARY KEY,
  `name_user` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Connect to Database

Connecting to the database using php pdo and mysql database, how to connect to the mysql database using php as below.

try {
    $host = 'localhost';
    $dbnm = 'cart';
    $user = 'root';
    $pass = '';
    $dbh = new PDO('mysql:host='.$host.';dbname='.$dbnm, $user, $pass);
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

Library for Shopping Cart

This library is for layout design and for shopping carts, for libraries still using the framework from Bootstrap, Awesome Fonts, jQuery and jQuery MyCart, these frameworks to support this shopping cart creation. For the code to call the framework library is as below.

<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<style>
        .badge-notify{
            background:red;
            position:relative;
            top: -10px;
            right: 10px;
        }
        .my-cart-icon-affix {
            position: fixed;
            z-index: 999;
        }
</style>

<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.mycart.min.js"></script>

View Products

View products to display products that have been stored into the database along with two buttons to see product details and for shopping, if the detail button is pressed it will display a modal dialog that will display complete info about the product, but if the shopping button is pressed means he has been shopping products And must check out for legitimate shopping.

<?php
include "config.php";
?>
<nav class="navbar navbar-default navbar-static-top">
      <div class="container">
        <div class="navbar-header">
          <a class="navbar-brand" href="#">
            <h2 style="margin-top:0;">Products</h2>
          </a>
        </div>
        <p class="navbar-text navbar-right"><i class="fa fa-shopping-cart fa-2x my-cart-icon"><span class="badge badge-notify my-cart-badge"></span></i></p>
        <p class="navbar-text navbar-right"><i class="fa fa-user fa-2x"></i> <a href="#" class="navbar-link">Tedir Ghazali</a></p>
        <p class="navbar-text navbar-right"><a href="order.php" class="navbar-link"><i class="fa fa-envelope fa-2x"></i></a></p>
      </div>
</nav>
    
<div class="container">
        <div class="row">
        <?php
        $stmt = $dbh->prepare("SELECT * FROM product");
        if ($stmt->execute()) {
            while ($row = $stmt->fetch()) {
        ?>
          <div class="col-sm-3 col-md-3">
            <div class="thumbnail">
              <img src="assets/images/<?php echo $row['image'] ?>" alt="<?php echo $row['name'] ?>" style="height:150px;width:100%;">
              <div class="caption text-center">
                <h3><?php echo $row['name'] ?></h3>
                <p><strong>Price</strong>: $<?php echo $row['price'] ?><br/><?php echo $row['summary'] ?></p>
                <p>
                    <button type="button" class="btn btn-danger my-cart-btn" data-id="<?php echo $row['id'] ?>" data-name="<?php echo $row['name'] ?>" data-summary="<?php echo $row['summary'] ?>" data-price="<?php echo $row['price'] ?>" data-quantity="<?php echo $row['quantity'] ?>" data-image="assets/images/<?php echo $row['image'] ?>">Add to Cart</button> 
                    <button type="button" class="btn btn-info" data-toggle="modal" data-target="#myModal-<?php echo $row['id'] ?>">Details</button>
                </p>
              </div>
            </div>
          </div>
            <!-- Modal -->
            <div class="modal fade" id="myModal-<?php echo $row['id'] ?>" tabindex="-<?php echo $row['id'] ?>" role="dialog" aria-labelledby="myModalLabel-<?php echo $row['id'] ?>">
              <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-<?php echo $row['id'] ?>"><?php echo $row['name'] ?></h4>
                  </div>
                  <div class="modal-body">
                    <img src="assets/images/<?php echo $row['image'] ?>" style="width:100%"/><br/>
                    <strong>Price</strong>: $<?php echo $row['price'] ?><br/>
                    <?php echo $row['summary'] ?>
                  </div>
                </div>
              </div>
            </div>
        <?php
            }
        }
        ?>
        </div>
</div>

jQuery Code for Shopping Cart

jQuery function is to run the shopping cart function so that when the shopping button is pressed it will automatically enter into an icon on the navbar with numbers or quantities purchased on one or more products, if the icon on the navbar is clicked it will appear modal dialog containing the product Purchased and checkout button. For syntax code as below.

$(function () {

    var goToCartIcon = function($addTocartBtn){
      var $cartIcon = $(".my-cart-icon");
      var $image = $('<img width="30px" height="30px" src="' + $addTocartBtn.data("image") + '"/>').css({"position": "fixed", "z-index": "999"});
      $addTocartBtn.prepend($image);
      var position = $cartIcon.position();
      $image.animate({
        top: position.top,
        left: position.left
      }, 500 , "linear", function() {
        $image.remove();
      });
    }

    $('.my-cart-btn').myCart({
      currencySymbol: '$',
      classCartIcon: 'my-cart-icon',
      classCartBadge: 'my-cart-badge',
      classProductQuantity: 'my-product-quantity',
      classProductRemove: 'my-product-remove',
      classCheckoutCart: 'my-cart-checkout',
      affixCartIcon: true,
      showCheckoutModal: true,
      /*cartItems: [
        {id: 1, name: 'Juice Blender', summary: 'Bisa blender jus, bumbu masakan', price: 10, quantity: 1, image: 'assets/images/img_1.png'},
        {id: 2, name: 'TV remote', summary: 'Bisa untuk semua tv', price: 20, quantity: 2, image: 'assets/images/img_2.png'},
        {id: 3, name: 'Sony camera', summary: 'Kamera murah', price: 30, quantity: 1, image: 'assets/images/img_3.png'}
      ],*/
      clickOnAddToCart: function($addTocart){
        goToCartIcon($addTocart);
      },
      afterAddOnCart: function(products, totalPrice, totalQuantity) {
        console.log("afterAddOnCart", products, totalPrice, totalQuantity);
      },
      clickOnCartIcon: function($cartIcon, products, totalPrice, totalQuantity) {
        console.log("cart icon clicked", $cartIcon, products, totalPrice, totalQuantity);
      },
      checkoutCart: function(products, totalPrice, totalQuantity) {
        var checkoutString = "Total Price: " + totalPrice + "\nTotal Quantity: " + totalQuantity;
        $.each(products, function(){
            shoppingcart(this.id, this.quantity, this.price * this.quantity);
        });
        console.log("checking out", products, totalPrice, totalQuantity);
      },
      getDiscountPrice: function(products, totalPrice, totalQuantity) {
        console.log("calculating discount", products, totalPrice, totalQuantity);
        return totalPrice * 0.99;
      }
    });

});

Save Order After Checkout

Store the product into the database after the checkout button is clicked like the syntax code below.

$user = $_POST['ui'];
$idpro = $_POST['id'];
$aq = $_POST['aq'];
$ap = $_POST['ap'];
$order = $_POST['order'];
$stmt = $dbh->prepare("INSERT INTO shopping VALUES (?,?,?,?,?)");
$stmt->bindParam(1, $user);
$stmt->bindParam(2, $idpro);
$stmt->bindParam(3, $aq);
$stmt->bindParam(4, $ap);
$stmt->bindParam(5, $order);
$stmt->execute();

The above code is a data transfer from jquery ajax to add data as below.

<?php
$angka = substr(uniqid(rand(), true), 7, 7);
$order = preg_replace("/[^0-9]/", "",$angka);
?>

function shoppingcart(allid,allquantity,allprice){
    var myorder = "<?php echo $order ?>";
    $.post('order.php',{ui:'1', id:allid, aq:allquantity, ap:allprice, shopping:'shopping', order:myorder});
}

View Order Product

View order product is a new page to display the order of products that have been purchased by the user, View order product is only displayed by user, so here do not use user login so the user only one with id is 1, In the order product view page there are products that have been purchased and will be displayed into the table the total price along with the discount, and in the page there is a button to cancel the order.

<div class="container">
        <h1>Tedir Ghazali</h1>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $stmt = $dbh->prepare("SELECT * FROM shopping a, product b where a.id=b.id and a.id_user = 1");
                if ($stmt->execute()) {
                  while ($row = $stmt->fetch()) {
                ?>
                <tr>
                    <td width="120"><img src="assets/images/<?php echo $row['image'] ?>" style="width:100px"/></td>
                    <td><strong><?php echo $row['name'] ?></strong></td>
                    <td width="80"><?php echo $row['amount_quantity'] ?></td>
                    <td width="80"><?php echo $row['amount_price'] ?></td>
                </tr>
                <?php
                  }
                }
                ?>
            </tbody>
            <tfoot>
                <?php
                $stmt2 = $dbh->prepare("SELECT sum(amount_price) as ap2 FROM shopping where id_user = 1");
                $stmt2->execute();
                $row2 = $stmt2->fetch();
                ?>
                <tr>
                    <th colspan="2">Total</th>
                    <th colspan="2"><?php echo $row2['ap2'] ?></th>
                </tr>
                <tr>
                    <th colspan="2">Total (including discount)</th>
                    <th colspan="2"><?php echo $row2['ap2']*0.99 ?></th>
                </tr>
            </tfoot>
        </table>
        <p class="text-right"><a href="index.php" class="btn btn-default">Back to homepage</a> <a href="?del=1" class="btn btn-danger">Cancel</a></p>
</div>

 

Thank you for visiting, hopefully useful and if you have any questions please ask the question menu and to download the source code below.

Shopping Cart With PHP and jQuery

Create Zip Archive File With PHP

Create Zip Archive File With PHP

Zip is a file format for data compression and as a standard format, zip is a file archive, the use zip archives is to compress many files or large files so that the file size becomes small and can save storage media and more efficient in file transfers or send files . It would be more difficult to transfer data if without using zip archives, because if sending large files takes large media storage space and takes a long time to file transfer process.

In addition, zip archives are also resistant to viruses that can damage the files in it, mostly due to the virus attack the affected zip file but the file there still survived, there is also a case of files in the zip archive has a virus but our computer stays safe if Does not run files in zip archives that are exposed to viruses.

Doing compression of many files or large files using zip archives is the right solution for manual data transfer such as using flash, data cable/lan, infrared or by using wireless and bluetooth. The compressed files remain safe from virus attacks, so it’s very safe and easy to use.

Next is how to create a zip file using php and how to read a zip file in the browser. How to create zip archives using php is like the explanation below.

Library for Layout Design

We need a template library to design the layout, we can use popular libraries like Bootstrap, Awesome Fonts, and DataTables, in addition you can also use Metro UI CSS, UIKit, W3CSS, MaterializeCSS and others. Below is a library that will be used to create a layout for zip archives with php.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script>
    $('table').dataTable();
</script>

Create Zip Archive File

Creating a zip file using php, here is not just one file that can be compressed into zip archives but also we can add folders or multiple files at once into the zip archive. To create a zip file, first create a design input form for the name of the zip file and the source of the folder or file, as below.

<form method="post">
    <div class="form-group">
        <label for="na">Name Archive</label>
        <div class="input-group">
           <input type="text" class="form-control" id="na" name="na" placeholder="phptoziparchiver" aria-describedby="basic-addon2">
           <span class="input-group-addon" id="basic-addon2">.zip</span>
        </div>
    </div>
    <div class="form-group">
        <label for="sr">Source</label>
        <input type="text" class="form-control" id="sr" name="sr" placeholder="C:\xampp\htdocs\project\phptoziparchiver"/>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block" id="an" name="an"/><i class="fa fa-plus"></i> Create New Archive</button>
   </div>
</form>

Make a folder to save the zip file, then make the execution of both form input using php, in order to compress the file or folder into the zip file automatically and save it into the folder that was created earlier. For the command code as below.

if(isset($_POST['an'])){
       $sr = $_POST['sr'];
       $na = $_POST['na'];
       $source = $sr;
       $filename = $na.".zip";
       class CustomArchive extends ZipArchive {
                public function addDir($location, $name) {
                    $this->addEmptyDir($name);
                    $this->addDirDo($location, $name);
                }
                private function addDirDo($location, $name) {
                    $name .= '/';         
                    $location .= '/';
                    $dir = opendir ($location);
                    while ($file = readdir($dir))    {
                        if ($file == '.' || $file == '..') continue;
                            $do = (filetype( $location . $file) == 'dir') ? 'addDir' : 'addFile';
                            $this->$do($location . $file, $name . $file);
                    }
                } 
       }

       $zip = new CustomArchive;
       $res = $zip->open("./archives/".$filename, ZipArchive::CREATE);
       if($res === TRUE)    {
           $zip->addDir($source, basename($source)); $zip->close();
       } else  { 
           echo 'Could not create a zip archive';
       }
}

Read File From Directory

Reading files from the zip file storage directory created using php, the function to make it easier for us to open zip files and view the contents in zip files, and with files that have been read in the browser can create a function to delete, add files or folder, create a password and etc.

Files that have been read from the directory will be displayed into a list containing the link address leading to the zip file open and link to remove the zip file from list and directory. To make it as below.

<ul class="list-group">
    <?php
         if ($handle = opendir('./archives')) {
             while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != "..") {
    ?>
                        <li class='list-group-item'>
                            <span onclick="window.location.href='?delfile=<?php echo $entry ?>'" class='badge'><i class='fa fa-trash'></i></span>
                            <a href='archiver.php?file=<?php echo $entry ?>'><?php echo $entry ?></a>
                        </li>
    <?php
                     }
             }
             closedir($handle);
         }
    ?>
</ul>

Remove File From Directory

Deleting files from directories and lists is necessary to remove unnecessary files in the directory but can also remove manuals in the directory by using Explorer on both Windows and Ubuntu / Mac OS X, for the syntax code as below.

<a href='archiver.php?file=<?php echo $entry ?>'><?php echo $entry ?></a>

<?php
if(isset($_GET['delfile'])){
       if(unlink('./archives/'.$_GET['delfile'])){
              echo "<script>location.href='index.php'</script>";
       }
}
?>

Open Zip Archive File

Open the zip archive file into the table using php, The contents of the zip archive file will be displayed into the table along with the root of the existing folder in the zip file as the example “text.txt file in the docs folder” it will be displayed to “docs/text.txt” On the table item. To syntax the table with php as below.

<table class="table table-striped table-hover">
    <thead>
         <tr>
             <th>File Name</th>
             <th>File Size</th>
             <th>Compressed Size</th>
             <th>Compression Method</th>
             <th>Action</th> 
         </tr>
    </thead>
    <tbody>
         <?php
         $za = zip_open('./archives/'.$zip);
         if ($za) {
               while ($zip_entry = zip_read($za)) {
         ?>
            <tr>
                 <td><?php echo $fn = zip_entry_name($zip_entry) ?></td>
                 <td><?php echo zip_entry_filesize($zip_entry) ?></td>
                 <td><?php echo zip_entry_compressedsize($zip_entry) ?></td>
                 <td><?php echo zip_entry_compressionmethod($zip_entry) ?></td>
                 <td>
                     <a target="_blank" href="function.php?file=<?php echo $zip ?>&exec=viewfile&src=<?php echo $fn ?>"><i class="fa fa-eye"></i></a> &nbsp;
                     <a href="function.php?file=<?php echo $zip ?>&exec=delfile&src=<?php echo $fn ?>"><i class="fa fa-trash"></i></a>
                 </td>
             </tr>
          <?php
               }
          }
          ?>
     </tbody>
</table>

Add New File and Create New Folder

Add a new file and create a new folder into an existing zip file. Can add files or create folders into zip files using php, Create an input form to add files and input form to create a folder, can also form created in the modal dialog, as below.

<button type="button" data-toggle="modal" data-target="#myModal-addfile" class="btn btn-primary"><i class="fa fa-file-o"></i> Add File</button>
<button type="button" data-toggle="modal" data-target="#myModal-addfolder" class="btn btn-success"><i class="fa fa-folder"></i> Add Folder</button>

<!-- Modal addfile -->
        <div class="modal fade" id="myModal-addfile" tabindex="-1" role="dialog" aria-labelledby="myModaladdfile">
            <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="myModaladdfile">Add File</h4>
                </div>
                <form method="get" action="function.php">
                <div class="modal-body">
                    <input type="hidden" name="file" value="<?php echo $zip ?>"/>
                    <input type="hidden" name="exec" value="addfile"/>
                    <div class="form-group">
                        <input type="text" name="des" class="form-control" placeholder="Add New File or Destination File"/>
                    </div>
                    <div class="form-group">
                        <input type="text" name="src" class="form-control" placeholder="Source New File"/>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Process</button>
                </div>
                </form>
                </div>
            </div>
        </div>
        <!-- Modal addfolder -->
        <div class="modal fade" id="myModal-addfolder" tabindex="-1" role="dialog" aria-labelledby="myModaladdfolder">
            <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="myModaladdfolder">Add Folder</h4>
                </div>
                <form method="get" action="function.php">
                <div class="modal-body">
                    <input type="hidden" name="file" value="<?php echo $zip ?>"/>
                    <input type="hidden" name="exec" value="addfolder"/>
                    <div class="form-group">
                        <input type="text" name="src" class="form-control" placeholder="Add New Folder"/>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Process</button>
                </div>
                </form>
                </div>
            </div>
</div>

Code execution command syntax to add new file and create new folder using php as below.

$zip = new ZipArchive;
$file = isset($_GET['file'])? $_GET['file'] : '';
$exec = isset($_GET['exec'])? $_GET['exec'] : '';
$src = isset($_GET['src'])? $_GET['src'] : '';
$des = isset($_GET['des'])? $_GET['des'] : '';
$res = $zip->open('./archives/'.$file);
if($exec == 'addfile'){
    if($zip->addFile($src, $des)){
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
} else if($exec == 'addfolder'){
    if($zip->addEmptyDir($src)) {
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
}

Extract to, Set Password, Comment and Download

Extract to is a function to extract existing files in a zip archive into another directory. Commonly called uncompress, set password is to provide a password for the zip file, comment is to comment for the zip file and download is get the zip file.

<button type="button" data-toggle="modal" data-target="#myModal-extracto" class="btn btn-warning"><i class="fa fa-file-archive-o"></i> Extract to</button>
<button type="button" data-toggle="modal" data-target="#myModal-setpassword" class="btn btn-danger"><i class="fa fa-key"></i> Set Password</button>
<button type="button" data-toggle="modal" data-target="#myModal-comment" class="btn btn-default"><i class="fa fa-comment"></i> Comment</button>
<a href="./archives/<?php echo $zip ?>" class="btn btn-info"><i class="fa fa-download"></i> Download</a>

<!-- Modal extracto -->
        <div class="modal fade" id="myModal-extracto" tabindex="-1" role="dialog" aria-labelledby="myModalextracto">
            <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="myModalextracto">Extract to</h4>
                </div>
                <form method="get" action="function.php">
                <div class="modal-body">
                    <input type="hidden" name="file" value="<?php echo $zip ?>"/>
                    <input type="hidden" name="exec" value="extracto"/>
                    <div class="form-group">
                        <input type="text" name="src" class="form-control" placeholder="Extract to ..."/>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Process</button>
                </div>
                </form>
                </div>
            </div>
        </div>
        <!-- Modal password -->
        <div class="modal fade" id="myModal-setpassword" tabindex="-1" role="dialog" aria-labelledby="myModalsetpassword">
            <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="myModalsetpassword">Set Password</h4>
                </div>
                <form method="get" action="function.php">
                <div class="modal-body">
                    <input type="hidden" name="file" value="<?php echo $zip ?>"/>
                    <input type="hidden" name="exec" value="setpassword"/>
                    <div class="form-group">
                        <input type="password" name="src" class="form-control" placeholder="Set Password"/>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Process</button>
                </div>
                </form>
                </div>
            </div>
        </div>
        <!-- Modal comment -->
        <div class="modal fade" id="myModal-comment" tabindex="-1" role="dialog" aria-labelledby="myModalcomment">
            <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="myModalcomment">Comment</h4>
                </div>
                <form method="get" action="function.php">
                <div class="modal-body">
                    <input type="hidden" name="file" value="<?php echo $zip ?>"/>
                    <input type="hidden" name="exec" value="comment"/>
                    <div class="form-group">
                        <textarea name="src" class="form-control" placeholder="Add Comment"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Process</button>
                </div>
                </form>
                </div>
            </div>
</div>

Next make execution for Extract to, Set Password, Command and Download using php, like syntax code below.

else if($exec == 'extracto'){
    if($zip->extractTo($src)){
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
} else if($exec == 'setpassword'){
    if($zip->setPassword($src)){
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
} else if($exec == 'comment'){
    if($zip->setArchiveComment($src)){
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
} else if($exec == 'viewfile'){
    echo $zip->getFromName($src);
    $zip->close();
} else if($exec == 'delfile'){
    if($zip->deleteName($src)){
        echo "<script>location.href='archiver.php?file=".$file."'</script>";
    }
    $zip->close();
} else if($exec == 'downloadfile'){
    /*header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$src);
    header('Content-Length: ' . filesize($src));
    readfile($src);*/
} else{
    echo "<script>location.href='index.php'</script>";
}

If you have questions please ask the question menu, please download the source code on how to create a zip archive file with php below.

Create Zip Archive File With PHP

CRUD Ajax and PHP Without Refresh Page

CRUD Ajax and PHP Without Refresh Page

 

CRUD is a familiar operating function for a web programmer, CRUD almost every web application available on the internet. Without CRUD it will be difficult to manage a data on the database. CRUD application is very important for a programmer because it is the framework of a web application.

CRUD stands for functions of Add / Create / New, Read / View, Edit / Update and Delete / Remove data from the database. The function is always there to connect the application form input to the database. Maybe, you can create CRUD with PHP and MySQL, but this tutorial we will implement how to make CRUD with jQuery Ajax and PHP MySQL without refresh page.

Creating CRUD with Ajax function is very nice because it makes our web application will be light and easy in inputting and displaying data from database, with Ajax function will also make page without refresh.

Create Database

You can create your own database with own table name and own item name, but if you want to like this tutorial is also not a problem, you can simply copy and paste the code below into your SQL execution like Phpmyadmin or Workbench.

CREATE DATABASE IF NOT EXISTS `mydata` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `mydata`;

CREATE TABLE `crud` (
  `id` int(11) NOT NULL PRIMARY KEY,
  `name` varchar(60) NOT NULL,
  `email` varchar(45) NOT NULL,
  `phone` varchar(20) NOT NULL,
  `address` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Layout Design (index.html)

You can design layouts for forms and tables by using Bootstrap, Metro UI CSS, UIKit, Semantic UI, MaterializeCSS and other CSS Framewok. In addition, you can also design with basic HTML5 / CSS3. Below is a layout design using Bootstrap for one page without refresh, and you can copy and paste to new file with name index.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>One Page CRUD Ajax</title>

    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/font-awesome.min.css" rel="stylesheet">
    <link href="assets/css/dataTables.bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
    
    <div class="container">
        <h3>One Page CRUD Ajax PHP/MySQL</h3>
        <div class="row">
            <div class="col-md-9">
                <table class="table table-bordered table-striped table-hover">
                    <thead>
                        <tr>
                            <th width="40">ID</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Address</th>
                            <th width="100">Action</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
            <div class="col-md-3">
                <form id="sidebar">
                    <div class="form-group">
                        <label for="id">ID</label>
                        <input type="number" id="id" name="id" class="form-control" placeholder="Identity"/>
                    </div>
                    <div class="form-group">
                        <label for="nm">Name</label>
                        <input type="text" id="nm" name="nm" class="form-control" placeholder="Full Name"/>
                    </div>
                    <div class="form-group">
                        <label for="em">Email</label>
                        <input type="email" id="em" name="em" class="form-control" placeholder="Your Email"/>
                    </div>
                    <div class="form-group">
                        <label for="hp">Phone Number</label>
                        <input type="tel" id="hp" name="hp" class="form-control" placeholder="Mobile Phone Number"/>
                    </div>
                    <div class="form-group">
                        <label for="ad">Address</label>
                        <textarea id="ad" name="ad" class="form-control" placeholder="Street Address"></textarea>
                    </div>
                    <button type="button" id="save" class="btn btn-primary" onclick="saveData()">Save</button>
                    <button type="button" id="update" class="btn btn-warning" onclick="updateData()">Update</button>
                </form>
            </div>
        </div>
    </div>

    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="assets/js/jquery.dataTables.min.js"></script>
    <script src="assets/js/dataTables.bootstrap.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

Connect to Database

The first time in making a web application is a connection between a web application with a database that you can create a special file with the name of config.php or connection.php or you can combine the connection with the other files such as this tutorial we combine into one file all functions both connections , add data, view data, edit update and delete data.

$dbh = new PDO('mysql:host=localhost;dbname=mydata', 'root', '');

Add/Create Data

To add data or create data, in this tutorial we will discuss how to implement or how to work added data into database by using ajax jquery and php, the data will be executed through input form which have id by clicking the button that there is javascript function that is onclick attribute, The data will be redirected to the saveData () function on the onclick attribute, for example the form below which has been given id on input and javascript function on the button.

<form id="sidebar">
      <div class="form-group">
            <label for="id">ID</label>
            <input type="number" id="id" name="id" class="form-control" placeholder="Identity"/>
      </div>
      <div class="form-group">
            <label for="nm">Name</label>
            <input type="text" id="nm" name="nm" class="form-control" placeholder="Full Name"/>
      </div>
      <div class="form-group">
            <label for="em">Email</label>
            <input type="email" id="em" name="em" class="form-control" placeholder="Your Email"/>
      </div>
      <div class="form-group">
            <label for="hp">Phone Number</label>
            <input type="tel" id="hp" name="hp" class="form-control" placeholder="Mobile Phone Number"/>
      </div>
      <div class="form-group">
            <label for="ad">Address</label>
            <textarea id="ad" name="ad" class="form-control" placeholder="Street Address"></textarea>
      </div>
      <button type="button" id="save" class="btn btn-primary" onclick="saveData()">Save</button>
</form>

The data will then be sent to the saveData() function (script.js) using javascript or jquery and in the saveData() function is Ajax for useful post data to send data to file server such as PHP, JSP, ASP.Net, Perl, Python and others.

function saveData(){
    var id = $('#id').val()
    var name = $('#nm').val()
    var email = $('#em').val()
    var phone = $('#hp').val()
    var address = $('#ad').val()
    $.post('server.php?p=add', {id:id, nm:name, em:email, hp:phone, ad:address}, function(data){
        viewData()
        $('#id').val(' ')
        $('#nm').val(' ')
        $('#em').val(' ')
        $('#hp').val(' ')
        $('#ad').val(' ')
    })
}

On a file server like php (server.php) is the place for execution of data into the database, data sent from saveData () will be executed here and will be stored into the database.

try{
        $id = $_POST['id'];
        $nm = $_POST['nm'];
        $em = $_POST['em'];
        $hp = $_POST['hp'];
        $ad = $_POST['ad'];
        $stmt = $dbh->prepare("INSERT INTO crud VALUES(?,?,?,?,?)");
        $stmt->bindParam(1,$id);
        $stmt->bindParam(2,$nm);
        $stmt->bindParam(3,$em);
        $stmt->bindParam(4,$hp);
        $stmt->bindParam(5,$ad);
        if($stmt->execute()){
            print "<div class='alert alert-success' role='alert'>Data has been added</div>";
        } else{
            print "<div class='alert alert-danger' role='alert'>Failed to add data</div>";
        }
} catch(PDOException $e){
        print "Error!: " . $e->getMessage() . "<br/>";
}

View/Read Data

Read data or view data is a function or operation to display data from the database into the table through php and ajax with no refresh when done data addition and data editing. You can create a table by providing with tbody tags like below.

<table class="table table-bordered table-striped table-hover">
    <thead>
        <tr>
            <th width="40">ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Address</th>
            <th width="100">Action</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

Next make it to the script.js file or it can be in the script tag a viewData () function to call data from php.

$('table').dataTable();
viewData();
$('#update').prop("disabled",true);

function viewData(){
    $.get('server.php', function(data){
        $('tbody').html(data)
    })
}

Then on the server.php file make the execution to call data from the database record.

try{
        $stmt = $dbh->prepare("SELECT * FROM crud ORDER BY id DESC");
        $stmt->execute();
        while($row = $stmt->fetch()){
            print "<tr>";
            print "<td>".$row['id']."</td>";
            print "<td>".$row['name']."</td>";
            print "<td>".$row['email']."</td>";
            print "<td>".$row['phone']."</td>";
            print "<td>".$row['address']."</td>";
            print "<td class='text-center'><div class='btn-group' role='group' aria-label='group-".$row['id']."'>";
            ?> 
            <button onclick="editData('<?php echo $row['id'] ?>','<?php echo $row['name'] ?>','<?php echo $row['email'] ?>','<?php echo $row['phone'] ?>','<?php echo $row['address'] ?>')" class='btn btn-warning'>Edit</button>
            <button onclick="removeConfirm('<?php echo $row['id'] ?>')" class='btn btn-danger'>Trash</button>
            <?php 
            print "</div></td>";
            print "</tr>";
        }
    } catch(PDOException $e){
        print "Error!: " . $e->getMessage() . "<br/>";
 }

Edit/Update Data

Edit data is a function of adding data by id to the input form, the data added comes from the table or from the database, whereas, update the data is to change the data from the input form and then change the data in the database record, to make the input form similar to the form Add / Create data just add below save button and to edit button already exist in Read / View Data.

<button type="button" id="update" class="btn btn-warning" onclick="updateData()">Update</button>

Then create the editData() and updateData() function, the editData() function only displays the data into the input form, updateData() function is the data execution button that will be sent to php.

function editData(id, nm, em, hp, ad) {
    $('#id').val(id)
    $('#nm').val(nm)
    $('#em').val(em)
    $('#hp').val(hp)
    $('#ad').val(ad)
    $('#id').prop("readonly",true);
    $('#save').prop("disabled",true);
    $('#update').prop("disabled",false);
}

function updateData(){
    var id = $('#id').val()
    var name = $('#nm').val()
    var email = $('#em').val()
    var phone = $('#hp').val()
    var address = $('#ad').val()
    $.post('server.php?p=update', {id:id, nm:name, em:email, hp:phone, ad:address}, function(data){
        viewData()
        $('#id').val(' ')
        $('#nm').val(' ')
        $('#em').val(' ')
        $('#hp').val(' ')
        $('#ad').val(' ')
        $('#id').prop("readonly",false);
        $('#save').prop("disabled",false);
        $('#update').prop("disabled",true);
    })
}

Then change the data in the database with the following command code.

try{
        $id = $_POST['id'];
        $nm = $_POST['nm'];
        $em = $_POST['em'];
        $hp = $_POST['hp'];
        $ad = $_POST['ad'];
        $stmt = $dbh->prepare("UPDATE crud SET name=?, email=?, phone=?, address=? WHERE id=?");
        $stmt->bindParam(1,$nm);
        $stmt->bindParam(2,$em);
        $stmt->bindParam(3,$hp);
        $stmt->bindParam(4,$ad);
        $stmt->bindParam(5,$id);
        if($stmt->execute()){
            print "<div class='alert alert-success' role='alert'>Data has been updated</div>";
        } else{
            print "<div class='alert alert-danger' role='alert'>Failed to update data</div>";
        }
    } catch(PDOException $e){
        print "Error!: " . $e->getMessage() . "<br/>";
}

Delete/Remove Data

In the delete data or remove data, we must create a confirmation button which means that every time the user will delete the data it will appear notification in the form of alerts or warnings to continue or cancel. For the function as below.

function deleteData(id){
    $.post('server.php?p=delete', {id:id}, function(data){
        viewData()
    })
}

function removeConfirm(id){
    var con = confirm('Are you sure, want to delete this data!');
    if(con=='1'){
        deleteData(id);
    }
}

Then when the delete button is clicked then immediately the data will be deleted from database without refresh page.

try{
        $id = $_POST['id'];
        $stmt = $dbh->prepare("DELETE FROM crud WHERE id=?");
        $stmt->bindParam(1,$id);
        if($stmt->execute()){
            print "<div class='alert alert-success' role='alert'>Data has been deleted</div>";
        } else{
            print "<div class='alert alert-danger' role='alert'>Failed to delete data</div>";
        }
} catch(PDOException $e){
        print "Error!: " . $e->getMessage() . "<br/>";
}

Thank you very much for visiting this website. Please download the source code below.

CRUD Ajax and PHP Without Refresh Page