UPDATE Y INSERT FORMATO FECHA MYSQL PHP JQUERY

 Basic AJAX CRUD app using PHP, MySQL and jQuery

CODE PHP DEVELOPMENT TUTORIALS January 23, 2021 4 Comments  SHARE 

3


We are going to build a basic AJAX CRUD app from scratch using only PHP, MySQL and jQuery AJAX. CRUD is an acronym for Create, Read, Update, Delete. Basic operations that are at the heart of all web apps.


We will use Bootstrap for the layout and utilize other jQuery plugins for the UI.


But first, the file structure.


/db – The directory that has all the server and database related files 


env.php – environment settings for database, server and miscellaneous display options

generate-db.php – creates a database based on the details set in the env. file

create-table.php -creates a table based on the details set in the env. file

connect-db.php – global include for databases connection

/api – The directory that has all endpoint related files 


create.php – all the code and mySQL statements for inserting records

delete.php – all the code and mySQL statements  for deleting records

index.php – all the code and mySQL statements  for showing rows based on the current page

update.php – all the code and mySQL statements  for updating records

/js/index.js – The file that handles all page events 


displayBookList() – displays the initial list of all books with pagination

displayPageEntries() – displays books for the current page

refreshList(data) –  universal function to refresh the content of the table, takes in data.

View book – has all the code to display a record

Create book – code to add a new record

Edit book  – all the code to fill in the edit form with current data

Update book – code to update a record

 /index.php – Is the main file that contains all elements, our app will use modal windows to display the forms. 



Let’s start.


Step 1: Take care of the database. These files are for global use but create-table.php and generate-db.php are used only once.


.env.php 


<?php

// Database info

$server = "localhost";

$user = "root";

$pass = "";

$db_name = "awesomedb";

$table_name = "books";


// Server URL

$url = "http://localhost/";


$display_rows = 10;


?>

generate-db.php 


<?php

include_once("env.php");


// Create connection

$connection = new mysqli($server, $user, $pass);


// Check connection

if ($connection->connect_error) {

    die("ERROR: Could not connect " . $connection->connect_error);

}


// Create new database

$sql = "CREATE DATABASE `$db_name`";


if($connection->query($sql) === TRUE){

    echo "Database created successfully";

} else {

    echo "ERROR: Unable to execute $sql. " . $connection->error;

}


// Close connection

$connection->close();


?>

create-table.php 


<?php

include_once("connect-db.php");


// Create new table

$sql = "CREATE TABLE `$table_name` (

            id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

            title VARCHAR(191) NOT NULL,

            author VARCHAR(191) NOT NULL,

            published_date DATE,

            last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

            status ENUM('active', 'pending', 'deleted')

        )";


if($connection->query($sql) === TRUE){

    echo "Table '".$table_name."' created successfully";

} else {

    echo "Error creating table: " . $connection->error;

}

 

// Close connection

$connection->close();


?>

connect-db.php 


<?php

include_once("env.php");


// Create connection

$connection = new mysqli($server, $user, $pass, $db_name);


// Check connection

if ($connection->connect_error) {

    die("ERROR: Could not connect " . $connection->connect_error);

}

 


?>

Step 2: Prepare the endpoints. These files run the mySQL queries for the operations. This is where the magic actually happens.


create.php 


<?php

require_once('../db/connect-db.php');


// Add new record

$sql = "INSERT INTO `$table_name` ( `title`, `author`, `published_date`) VALUES ( '".$_POST['title']."', '".$_POST['author']."', '".$_POST['published_date']."')";

$result = $connection->query($sql);


// Return value

$sql = "SELECT * FROM $table_name ORDER BY id DESC LIMIT 1";

$result = $connection->query($sql);

$data = $result->fetch_assoc();

echo json_encode($data);

?>

index.php 


<?php

require_once('../db/connect-db.php');

 

$page = (isset($_GET["page"])) ? $_GET["page"] : 1;

$start_from = ($page-1) * $display_rows;


// Get all rows for selected page

$sql = "SELECT * FROM $table_name ORDER BY id DESC LIMIT $start_from, $display_rows";

$result = $connection->query($sql);

while($row = $result->fetch_assoc()){

    $json[] = $row;

}

$data['data'] = $json;


// Get total count of all books

$sql = "SELECT COUNT(*) AS total FROM $table_name";

$result = $connection->query($sql);

$values = mysqli_fetch_assoc($result);

$data['total'] = $values['total'];


// Return books

echo json_encode($data);

?>

update.php 


<?php

require_once('../db/connect-db.php');


// Update record

$sql = "UPDATE `$table_name` SET `title` = '".$_POST['title']."', `author` = '".$_POST['author']."', `published_date` = '".$_POST['published_date']."' WHERE `id` = ".$_POST['id']."";

$result = $connection->query($sql);


// Return value

$sql = "SELECT * FROM $table_name WHERE `id` = '".$_POST['id']."'";

$result = $connection->query($sql);

$data = $result->fetch_assoc();

echo json_encode($data);

?>

delete.php 


<?php

require_once('../db/connect-db.php');

$id  = $_POST["id"];


// Delete record

$sql = "DELETE FROM $table_name WHERE id = '".$id."'";


if($connection->query($sql) === TRUE){

    echo json_encode([$id]);

} else {

    echo "Error deleting record " . $connection->error;

}


// Close connection

$connection->close(); 

?>

Step 3: Design the user interface. Page elements like lists, pagination, buttons and modal windows allows for user interaction. We used a few jQuery plugins to improve  the UI like twbsPagination, bootstrap-validator, jQueryUI and toast to display notifications 




index.php 


<?php require_once("db/env.php"); ?>

<!doctype html>

<html lang="en">

    <head>

        <!-- Meta tags -->

        <meta charset="utf-8">

        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">


        <!-- CSS -->

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

        <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">


        <!-- JS -->

        <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/twbs-pagination/1.4.2/jquery.twbsPagination.min.js" integrity="sha512-frFP3ZxLshB4CErXkPVEXnd5ingvYYtYhE5qllGdZmcOlRKNEPbufyupfdSTNmoF5ICaQNO6SenXzOZvoGkiIA==" crossorigin="anonymous"></script>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.min.js"></script>

    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>

        <link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">


        <!-- Custom JS  -->

        <script type="text/javascript">

            var url = "<?php echo $url; ?>";

            var display_rows = "<?php echo $display_rows; ?>";


            $(function(){

                $("#published_date").datepicker({ dateFormat: 'yy-mm-dd' });

                $("#published_date_edit").datepicker({ dateFormat: 'yy-mm-dd' });

            });

        </script>


        <!-- API JS files -->

        <script src="js/index.js"></script>


        <title>Trial Project for Worker Bee TV - Submitted by Jay Acab chiefofstack.com </title>

    </head>

    <body>

        <div class="container">

            <div class="row mt-4">

        <div class="col-lg-12">

            <div class="float-left">

                <h2>Books</h2>

            </div>

            <div class="float-right">

        <button type="button" class="btn btn-success" data-toggle="modal" data-target="#create-book">

        Add New Book

        </button>

            </div>

        </div>

    </div>


    <table class="table table-bordered table-striped text-muted text-center mt-3">

    <thead>

        <tr>

        <th>Date Published</th>

        <th>Author name</th>

                        <th>Book Title</th>

        <th>Action</th>

        </tr>

    </thead>

    <tbody>

    </tbody>

    </table>


    <ul id="pagination" class="pagination-sm"></ul>

        </div>


        <!-- View Book Modal -->

        <div id="view-book" class="modal"  tabindex="-1" role="dialog" aria-labelledby="modalLabel">

            <div class="modal-dialog" role="document">

                <div class="modal-content">

                    <div class="modal-header">

                        <div>

                            <h4 class="modal-title float-left" id="modalLabel">Book Information</h4>

                        </div>

                        <div>

                            <button type="button" class="close float-right" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>

                        </div>

                    </div>

                    <div class="modal-body">

                        <form id="view-book-form" data-toggle="validator" action="api/create.php" method="POST">

                            <div class="form-group">

                                <label class="control-label" for="title">Title:</label>

                                <p id="title_view" name="title" class="font-weight-bold" /></p>

                            </div>

                            <div class="form-group">

                                <label class="control-label" for="author">Author:</label>

                                <p id="author_view" name="author"  class="font-weight-bold"/></p>

                            </div>

                            <div class="form-group">

                                <label class="control-label" for="published_date">Date Published:</label>

                                <p id="published_date_view" name="published_date" class="font-weight-bold" /></p>

                            </div>

                            <div class="form-group">

                                <label class="control-label" for="id">ID:</label>

                                <p id="id_view" name="id" class="font-weight-bold" /></p>

                            </div>

                        </form>

                    </div>

                </div>

            </div>

        </div>


        <!-- Create Book Modal -->

        <div id="create-book" class="modal"  tabindex="-1" role="dialog" aria-labelledby="modalLabel">

            <div class="modal-dialog" role="document">

                <div class="modal-content">

                    <div class="modal-header">

                        <div>

                            <h4 class="modal-title float-left" id="modalLabel">Add a Book</h4>

                        </div>

                        <div>

                            <button type="button" class="close float-right" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>

                        </div>

                    </div>

                    <div class="modal-body">

                        <form id="create-book-form" data-toggle="validator" action="api/create.php" method="POST">

                            <div class="form-group">

                                <label class="control-label" for="title">Title:</label>

                                <input type="text" id="title" name="title" class="form-control" data-error="Please enter book title." required />

                                <div class="help-block with-errors text-danger"></div>

                            </div>

                            <div class="form-group">

                                <label class="control-label" for="author">Author:</label>

                                <input type="text" id="author" name="author" class="form-control" data-error="Please enter the name of the author." required>

                                <div class="help-block with-errors text-danger"></div>

                            </div>

                            <div class="form-group">

                                <label class="control-label" for="published_date">Date Published:</label>

                                <input type="text" id="published_date" name="published_date" class="form-control" data-error="Please enter the date when the book was published." required autocomplete="off">

                                <div class="help-block with-errors text-danger"></div>

                            </div>

                            <div class="form-group mt-4">

                                <button type="submit" class="btn submit-book btn-success">Submit</button>

                            </div>

                        </form>

                    </div>

                </div>

            </div>

        </div>


        <!-- Edit Book Modal -->

        <div id="edit-book" class="modal"  tabindex="-1" role="dialog" aria-labelledby="modalLabel">

            <div class="modal-dialog" role="document">

                <div class="modal-content">

                    <div class="modal-header">

                        <div>

                            <h4 class="modal-title float-left" id="modalLabel">Edit Book</h4>

                        </div>

                        <div>

                            <button type="button" class="close float-right" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>

                        </div>

                    </div>

                    <div class="modal-body">

                        <form id="edit-book-form" data-toggle="validator" action="api/update.php" method="put">

                            <input type="hidden" id="id" name="id" class="edit-id">

                            <div class="form-group">

                                <label class="control-label" for="title_edit">Title:</label>

                                <input type="text" id="title_edit" name="title" class="form-control" data-error="Please enter book title." required />

                                <div class="help-block with-errors text-danger"></div>

                            </div>

                            <div class="form-group">

                                <label class="control-label" for="author_edit">Author:</label>

                                <input type="text" id="author_edit" name="author" class="form-control" data-error="Please enter the name of the author." required>

                                <div class="help-block with-errors text-danger"></div>

                            </div>

                            <div class="form-group">

                                <label class="control-label" for="published_date_edit">Date Published:</label>

                                <input type="text" id="published_date_edit" name="published_date" class="form-control" data-error="Please enter the date when the book was published." required autocomplete="off">

                                <div class="help-block with-errors text-danger"></div>

                            </div>

                            <div class="form-group mt-4">

                                <button type="submit" class="btn submit-book-edit btn-success">Submit</button>

                            </div>

                        </form>

                    </div>

                </div>

            </div>

        </div>


    </body>

</html>

Step 4: Handle the events. This file brings your page to life. It connects page events to the endpoints to complete the operation.


index.js 


$(document).ready(function() {


/* Initialize the index */

var page = 1;

var current_page = 1;

var total_page = 0;

var display = "list";


/* Display Initial List of Books */

if(display=="list")

    displayBookList();

 

/* View book */

$("body").on("click",".view-book",function(){

    var id = $(this).parent("td").data('id');

    var title = $(this).parent("td").prev("td").text();

    var author = $(this).parent("td").prev("td").prev("td").text();

    var published_date = $(this).parent("td").prev("td").prev("td").prev("td").text();

    display = "details";


    $("#id_view").text(id);

    $("#title_view").text(title);

    $("#author_view").text(author);

    $("#published_date_view").text(published_date);

});


/* Create new book */

$('#create-book-form').on('submit', function(e){

    e.preventDefault();

    var form_action = $("#create-book-form").attr("action");

    var title = $("#title").val();

    var author = $("#author").val();

    var published_date = $("#published_date").val();

    display = "create";


    if(title != '' && author != '' && published_date !=''){

        $.ajax({

            dataType: 'json',

            type:'POST',

            url: url + form_action,

            data:{

                title:title,

                author:author,

                published_date:published_date

            }

        }).done(function(data){

            // Reset Form

            $("#title").val('');

            $("#author").val('');

            $("#published_date").val('');


            // Display new item on the list

            displayPageEntries();


            // Hide modal

            $("#create-book").modal('hide');

            toastr.success('Item Created Successfully.', 'Success Alert', {timeOut: 5000});

        });

    }else{

        alert('All fields are required. Please make sure you fill out all fields correctly.')

    }

});


/* Edit book */

$("body").on("click",".edit-book",function(){

    var id = $(this).parent("td").data('id');

    var title = $(this).parent("td").prev("td").text();

    var author = $(this).parent("td").prev("td").prev("td").text();

    var published_date = $(this).parent("td").prev("td").prev("td").prev("td").text();

    display = "edit";


    $("#title_edit").val(title);

    $("#author_edit").val(author);

    $("#published_date_edit").val(published_date);

    $("#edit-book-form").find(".edit-id").val(id);

});


/* Update book */

$('#edit-book-form').on('submit', function(e){

    e.preventDefault();


    var form_action = $("#edit-book-form").attr("action");

    var title = $("#title_edit").val();

    var author = $("#author_edit").val();

    var published_date = $("#published_date_edit").val();

    var id = $("#edit-book-form").find(".edit-id").val();



    if(title != '' && author != '' && published_date !=''){

        $.ajax({

            dataType: 'json',

            type:'POST',

            url: url + form_action,

            data:{

                id:id,

                title:title,

                author:author,

                published_date:published_date

            }

        }).done(function(data){

            // Reset Form

            $("#title_edit").val('');

            $("#author_edit").val('');

            $("#published_date_edit").val('');


            // Display new item on the list

            displayPageEntries();


            // Hide modal

            $("#edit-book").modal('hide');

            toastr.success('Item Updated Successfully.', 'Success Alert', {timeOut: 5000});

        });

    }else{

        alert('All fields are required. Please make sure you fill out all fields correctly.')

    }


});


/* Delete book */

$("body").on("click",".delete-book",function(){

    var id = $(this).parent("td").data('id');

    $.ajax({

        dataType: 'json',

        type:'POST',

        url: url + 'api/delete.php',

        data:{ id:id }

    }).done(function(data){

        displayPageEntries();

        toastr.success('Item Deleted Successfully.', 'Success Alert', {timeOut: 5000});

    });

});


/* Display initial list of all books with pagination */

function displayBookList() {

    $.ajax({

        dataType: 'json',

        url: url+'api/index.php',

        data: {page:page}

    }).done(function(data){

    total_page = Math.ceil(data.total/display_rows);

    current_page = page;

    refreshList(data.data);



        $('#pagination').twbsPagination({

        totalPages: total_page,

        visiblePages: current_page,

        onPageClick: function (event, pageL) {

        page = pageL;


                    displayPageEntries();


        }

    });


    });

}


/* Display books for current page*/

function displayPageEntries() {

$.ajax({

    dataType: 'json',

    url: url+'api/index.php',

    data: {page:page}

}).done(function(data){

refreshList(data.data);

});

}


/* Refresh table list  */

function refreshList(data) {

var rows = '';

$.each(data,function(key,value) {

  rows = rows + '<tr>';

  rows = rows + '<td>'+value.published_date+'</td>';

  rows = rows + '<td>'+value.author+'</td>';

        rows = rows + '<td>'+value.title+'</td>';

  rows = rows + '<td data-id="'+value.id+'">';

        rows = rows + '<button data-toggle="modal" data-target="#view-book" class="btn btn-primary btn-sm view-book">View Details</button> ';

        rows = rows + '<button data-toggle="modal" data-target="#edit-book" class="btn btn-primary btn-sm edit-book">Edit Book</button> ';

        rows = rows + '<button class="btn btn-danger btn-sm delete-book">Delete</button>';

        rows = rows + '</td>';

  rows = rows + '</tr>';

});

$("tbody").html(rows);

}


});




///////////////////////////////////////


Jquery


<script>

$(document).ready(function() {

$("#datepicker").datepicker({

    dateFormat: 'yy-mm-dd'

    });

})




<input type="text" id="datepicker" value="<?php echo $orders['date_payed']; ?>"/>

JS:


<script type="text/javascript">

    $(document).ready(function () {

        $("#datepicker").datepicker({

            dateFormat: "yy-mm-dd",

            onSelect: function () {

                var date = $("#datepicker").val();


                $.ajax({

                     type: "POST", //or GET. Whichever floats your boat.

                     url: "path/to/process_page.php",

                     data: { date: date },

                     success: function(data) {

                         alert(data);


                         //Write code here for you successful update (if you want to)

                     },

                     error: function() {

                         alert("Error.");

                     }

                });

            }

        });

    });

</script>



/////////////////////////////////////////////////////////



index.php



<?php  

 $connect = mysqli_connect("localhost", "root", "", "testing");  

 $query = "SELECT * FROM tbl_order ORDER BY order_id desc";  

 $result = mysqli_query($connect, $query);  

 ?>  

 <!DOCTYPE html>  

 <html>  

      <head>  

           <title>Webslesson Tutorial | Ajax PHP MySQL Date Range Search using jQuery DatePicker</title>  

           <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  

           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  

           <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>  

           <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  

      </head>  

      <body>  

           <br /><br />  

           <div class="container" style="width:900px;">  

                <h2 align="center">Ajax PHP MySQL Date Range Search using jQuery DatePicker</h2>  

                <h3 align="center">Order Data</h3><br />  

                <div class="col-md-3">  

                     <input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" />  

                </div>  

                <div class="col-md-3">  

                     <input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" />  

                </div>  

                <div class="col-md-5">  

                     <input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" />  

                </div>  

                <div style="clear:both"></div>                 

                <br />  

                <div id="order_table">  

                     <table class="table table-bordered">  

                          <tr>  

                               <th width="5%">ID</th>  

                               <th width="30%">Customer Name</th>  

                               <th width="43%">Item</th>  

                               <th width="10%">Value</th>  

                               <th width="12%">Order Date</th>  

                          </tr>  

                     <?php  

                     while($row = mysqli_fetch_array($result))  

                     {  

                     ?>  

                          <tr>  

                               <td><?php echo $row["order_id"]; ?></td>  

                               <td><?php echo $row["order_customer_name"]; ?></td>  

                               <td><?php echo $row["order_item"]; ?></td>  

                               <td>$ <?php echo $row["order_value"]; ?></td>  

                               <td><?php echo $row["order_date"]; ?></td>  

                          </tr>  

                     <?php  

                     }  

                     ?>  

                     </table>  

                </div>  

           </div>  

      </body>  

 </html>  

 <script>  

      $(document).ready(function(){  

           $.datepicker.setDefaults({  

                dateFormat: 'yy-mm-dd'   

           });  

           $(function(){  

                $("#from_date").datepicker();  

                $("#to_date").datepicker();  

           });  

           $('#filter').click(function(){  

                var from_date = $('#from_date').val();  

                var to_date = $('#to_date').val();  

                if(from_date != '' && to_date != '')  

                {  

                     $.ajax({  

                          url:"filter.php",  

                          method:"POST",  

                          data:{from_date:from_date, to_date:to_date},  

                          success:function(data)  

                          {  

                               $('#order_table').html(data);  

                          }  

                     });  

                }  

                else  

                {  

                     alert("Please Select Date");  

                }  

           });  

      });  

 </script>



filter.php



<?php  

 //filter.php  

 if(isset($_POST["from_date"], $_POST["to_date"]))  

 {  

      $connect = mysqli_connect("localhost", "root", "", "testing");  

      $output = '';  

      $query = "  

           SELECT * FROM tbl_order  

           WHERE order_date BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."'  

      ";  

      $result = mysqli_query($connect, $query);  

      $output .= '  

           <table class="table table-bordered">  

                <tr>  

                     <th width="5%">ID</th>  

                     <th width="30%">Customer Name</th>  

                     <th width="43%">Item</th>  

                     <th width="10%">Value</th>  

                     <th width="12%">Order Date</th>  

                </tr>  

      ';  

      if(mysqli_num_rows($result) > 0)  

      {  

           while($row = mysqli_fetch_array($result))  

           {  

                $output .= '  

                     <tr>  

                          <td>'. $row["order_id"] .'</td>  

                          <td>'. $row["order_customer_name"] .'</td>  

                          <td>'. $row["order_item"] .'</td>  

                          <td>$ '. $row["order_value"] .'</td>  

                          <td>'. $row["order_date"] .'</td>  

                     </tr>  

                ';  

           }  

      }  

      else  

      {  

           $output .= '  

                <tr>  

                     <td colspan="5">No Order Found</td>  

                </tr>  

           ';  

      }  

      $output .= '</table>';  

      echo $output;  

 }  

 ?>



Database



--  

 -- Table structure for table `tbl_order`  

 --  

 CREATE TABLE IF NOT EXISTS `tbl_order` (  

  `order_id` int(11) NOT NULL AUTO_INCREMENT,  

  `order_customer_name` varchar(255) NOT NULL,  

  `order_item` varchar(255) NOT NULL,  

  `order_value` double(12,2) NOT NULL,  

  `order_date` date NOT NULL,  

  PRIMARY KEY (`order_id`)  

 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;  

 --  

 -- Dumping data for table `tbl_order`  

 --  

 INSERT INTO `tbl_order` (`order_id`, `order_customer_name`, `order_item`, `order_value`, `order_date`) VALUES  

 (1, 'David E. Gary', 'Shuttering Plywood', 1500.00, '2016-10-14'),  

 (2, 'Eddie M. Douglas', 'Aluminium Heavy Windows', 2000.00, '2016-10-08'),  

 (3, 'Oscar D. Scoggins', 'Plaster Of Paris', 150.00, '2016-09-29'),  

 (4, 'Clara C. Kulik', 'Spin Driller Machine', 350.00, '2016-09-30'),  

 (5, 'Christopher M. Victory', 'Shopping Trolley', 100.00, '2016-10-01'),  

 (6, 'Jessica G. Fischer', 'CCTV Camera', 800.00, '2016-10-02'),  

 (7, 'Roger R. White', 'Truck Tires', 2000.00, '2016-09-28'),  

 (8, 'Susan C. Richardson', 'Glass Block', 200.00, '2016-10-04'),  

 (9, 'David C. Jury', 'Casing Pipes', 500.00, '2016-09-27'),  

 (10, 'Lori C. Skinner', 'Glass PVC Rubber', 1800.00, '2016-09-30'),  

 (11, 'Shawn S. Derosa', 'Sony HTXT1 2.1-Channel TV', 180.00, '2016-10-03'),  

 (12, 'Karen A. McGee', 'Over-the-Ear Stereo Headphones ', 25.00, '2016-10-01'),  

 (13, 'Kristine B. McGraw', 'Tristar 10" Round Copper Chef Pan with Glass Lid', 20.00, '2016-09-30'),  

 (14, 'Gary M. Porter', 'ROBO 3D R1 Plus 3D Printer', 600.00, '2016-10-02'),  

 (15, 'Sarah D. Hunter', 'Westinghouse Select Kitchen Appliances', 35.00, '2016-09-29'),  

 (16, 'Diane J. Thomas', 'SanDisk Ultra 32GB microSDHC', 12.00, '2016-10-05'),  

 (17, 'Helena J. Quillen', 'TaoTronics Dimmable Outdoor String Lights', 16.00, '2016-10-04'),  

 (18, 'Arlette G. Nathan', 'TaoTronics Bluetooth in-Ear Headphones', 25.00, '2016-10-03'),  

 (19, 'Ronald S. Vallejo', 'Scotchgard Fabric Protector, 10-Ounce, 2-Pack', 20.00, '2016-10-03'),  

 (20, 'Felicia L. Sorensen', 'Anker 24W Dual USB Wall Charger with Foldable Plug', 12.00, '2016-10-04');


</script>


/////////////////////////////////////////////////////////

https://www.appsloveworld.com/mysql/100/213/update-mysql-database-fields-with-datepicker-jquery-ajax-php

'm assuming what you are asking is that you want the datepicker to update your MySQL table when you select on a date without having to refresh that page. The code you provided is a little confusing, but I put something together that may help.


I am guessing that the input field that's in your code is actually supposed to be the html where you are getting the value.


As for keeping it all on one single page... I don't think that will be possible. For best results, you will have to make a new .php page to accept the value of the datepicker, which is passed through the $.ajax call where it says date. If you did it on the same page, there's a possibility you may end up getting a swamp of unwanted html data returned to you via the data parameter in the success function, but it would most likely throw an error and get the error function callback.


In this example, I called the php page process_date.php.


HTML:


<input type="text" id="datepicker" value="<?php echo $orders['date_payed']; ?>"/>

JS:


<script type="text/javascript">

    $(document).ready(function () {

        $("#datepicker").datepicker({

            dateFormat: "yy-mm-dd",

            onSelect: function () {

                var date = $("#datepicker").val();


                $.ajax({

                     type: "POST", //or GET. Whichever floats your boat.

                     url: "path/to/process_page.php",

                     data: { date: date },

                     success: function(data) {

                         alert(data);


                         //Write code here for you successful update (if you want to)

                     },

                     error: function() {

                         alert("Error.");

                     }

                });

            }

        });

    });

</script>

Crud System Using Ajax jQuery PHP ...


Pause


Unmute

Remaining Time -13:00



Fullscreen

Now Playing

Crud System Using Ajax jQuery PHP MySQL part 2


Point of sales system Using Ajax jQuery PHP MySQL part 36

29:28


Point of sales system Using Ajax jQuery PHP MySQL part 29 load vendors

13:28


Point of sales system Using Ajax jQuery PHP MySQL part 39 Qty increment

15:33


Point of sales system Using Ajax jQuery PHP MySQL part 41 Sales

21:43


Point of sales system Using Ajax jQuery PHP MySQL part 28 Get Product Details

26:59


Point of sales system Using Ajax jQuery PHP MySQL part 27 Purchase form creation continue

9:20


Point of sales system Using Ajax jQuery PHP MySQL part 30 Purchase item

19:16


Point of sales system Using Ajax jQuery PHP MySQL part 40 Qty decrement

7:52


How to Insert Data using PHP Ajax

6:12

Play Video

PHP (process_date.php)


<?php


    $date = $_POST['date'];  //if you used GET in your ajax, then use $_GET here instead



    $query = $this->db->query("select * from oc_order");


    ***code left out to save space***


    foreach ($products as $orders) {

        print $orders['order_id'];


        $query = $this->db->query("update oc_order SET date_payed='$date' WHERE  order_id='$orders['order_id'];'");


        echo "Success";

    }

?>

Note: Not saying you didn't, but don't forget to always sanitize your PHP data before sending it to the server in order to avoid being attacked via SQL Injection. Even if you use parameterized queries, it is still a good idea.



///////////////////////////////////////


How To Use Bootstrap Datepicker in PHP &amp; MySQL using Ajax

Visit codeanddeploy.com and access the sample code by following the link for utilizing MSDT_A1 with AJAX in MSDT_A2, posted on their PHP blog.


This guide will demonstrate the implementation of Bootstrap Datepicker in PHP & MySQL with the assistance of Ajax. The process will be explained in a step-by-step manner. For instance, we will develop a function that solicits the users' date of birth.


By utilizing bootstrap datepicker , we facilitate a prompt procedure that boasts an exceptional user interface, instead of starting from scratch or relying solely on Chrome's default date picker, which lacks support for other browsers.


Before we proceed with this tutorial, it's important to mention the tools we'll be working with. We'll be using Bootstrap 4, jQuery 3.5.1, and the Bootstrap datepicker framework.


Index.html File

Below is the entire source code for our index.html.




 lang="en">


    How To Use Bootstrap Datepicker in PHP & MySQL using Ajax

    

     rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    

     rel="stylesheet" href="assets/plugins/bootstrap-datepicker/css/bootstrap-datepicker.min.css">



     class="container">

        



        

How To Use Bootstrap Datepicker in PHP & MySQL using Ajax

        



         action="process.php" id="form">

             class="form-group">

                 for="email">Date Of Birth:

                 class="date form-control" type="text" name="date-of-birth">

            

type= "button" class= "btn btn-primary" id= "btnSubmit" > Submit

Script.js File

Afterwards, we imported the above code into our javascript called scripts.js. Please refer to the comments on each line to comprehend the procedure.


$(document).ready(function() {

    // Initialize the datepicker

    $('.date').datepicker({

        todayHighlight: true, // to highlight the today's date

        format: 'yyyy-mm-dd', // we format the date before we will submit it to the server side

        autoclose: true //we enable autoclose so that once we click the date it will automatically close the datepicker

    }); 

    $("#btnSubmit").on("click", function() {

        var $this           = $("#btnSubmit"); //submit button selector using ID

        var $caption        = $this.html();// We store the html content of the submit button

        var form            = "#form"; //defined the #form ID

        var formData        = $(form).serializeArray(); //serialize the form into array

        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config

        $.ajax({

            type: "POST", //we are using POST method to submit the data to the server side

            url: route, // get the route value

            data: formData, // our serialized array data for server side

            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click

                $this.attr('disabled', true).html("Processing...");

            },

            success: function (response) {//once the request successfully process to the server side it will return result here

                $this.attr('disabled', false).html($caption);

                // We will display the result using alert

                alert(response);

            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {

                // You can put something here if there is an error from submitted request

            }

        });

    });

});


Ezoic

Creating Database Table

Afterwards, we will proceed to form our database table . Assuming that your database is already established, the next step is to create a table named "dob", using the code provided below.


CREATE TABLE `dob` (

  `id` int(11) NOT NULL,

  `dob` date NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Process.php File

Finally, we have the concluding code to handle the storage of the data submitted via our form.


Ezoic


    $request = $_REQUEST; //a PHP Super Global variable which used to collect data after submitting it from the form

    $date = $request['date-of-birth']; //get the date of birth from collected data above

    $servername = "localhost"; //set the servername

    $username = "root"; //set the server username

    $password = ""; // set the server password (you must put password here if your using live server)

    $dbname = "demos"; // set the table name

    // Create connection

    $conn = mysqli_connect($servername, $username, $password, $dbname);

    // Check connection

    if (!$conn) {

      die("Connection failed: " . mysqli_connect_error());

    }

    // Set the INSERT SQL data

    $sql = "INSERT INTO dob (dob)

    VALUES ('".$date."')";

    // Process the query so that we will save the date of birth

    if (mysqli_query($conn, $sql)) {

      echo "New record created successfully.";

    } else {

      return "Error: " . $sql . "

" . mysqli_error($conn);

    }

    // Close the connection after using it

    mysqli_close($conn);

?>


Ezoic

By utilizing Ajax, PHP, and MySQL, it is now possible to store information obtained from Bootstrap's datepicker.


This tutorial may be beneficial to you. If you wish to obtain the code, please go to this website: https://codeanddeploy.com/blog/php/how-to-use-bootstrap-datepicker-in-php-mysql-using-ajax.


How To Use Bootstrap Datepicker in PHP & MySQL, Here is the code below. CREATE TABLE `dob` ( `id` int (11) NOT NULL, `dob` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; Process.php File Next, our last code to process the saving of submitted data from our from.

Bootstrap 4.5 datepicker

date picker for bootstrap 4

$('.datepicker').datepicker({

    format: 'mm/dd/yyyy',

    startDate: '-3d'

});

Ezoic

date picker for bootstrap 4


    


    


        

    



Datepicker bootstrap 4 tutorial Code Example, <input class="datepicker" data-date-format="mm/dd/yyyy">

Date picker with bootstrap 4

date picker for bootstrap 4


    


    


        

    



Bootstrap 4 datepicker Code Example, bootstrap 4 date datepicker bootstrap 4 datatime picker bootstaro date picker boostrap date picker.js <div class='input-group datepicker ' data-format="L"> enter date manually in bsdatepicker date picker bootstrap 4 templete date picker html bootstrap 4 with all assets date picker example bootstrap 4 …

Bootstrap-datetimepicker example

bootstrap datepicker date format

//Bootstrap datepicker change date format solution , Jquery datepicker is under this solution

If by ID: just change "#datepicker" to your input field id

$('#datepicker').datepicker({

    format: 'dd/mm/yyyy'

});

If by Class: just change "#datepicker" to your input field class

$('.datepicker').datepicker({

    format: 'dd/mm/yyyy'

});

//jquery datepicker change date format solution

just change "#datepicker" to your input field id

$("#datepicker").datepicker({

 

dateFormat: 'dd-mm-yy'

});

bootstrap datepicker format

02-16-2012


Get bootstrap 4 datepicker Code Example, datepicker html bootstrap. bootstrap for datepicker. boostrap 4 date picker. bootstrap .datepicker ( {}); timepicker js bootstrap. bootstrap form with datepicker. date time selector bootstrap 4. customize date picker html bootstrap. datepicker for bootstrap 4.






////////////////////


https://codeanddeploy.com/blog/php/how-to-use-bootstrap-datepicker-in-php-mysql-using-ajax



Index.html File

Here is the complete source code of our index.html


 


<!doctype html>

<html lang="en">

<head>

  <title>How To Use Bootstrap Datepicker in PHP & MySQL using Ajax</title>


  <!-- Bootstrap CSS -->

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<!-- Bootstra Datepicker CSS -->

<link rel="stylesheet" href="assets/plugins/bootstrap-datepicker/css/bootstrap-datepicker.min.css">

  

</head>

  

<body>

   

<div class="container">


<br><br>


    <h1>How To Use Bootstrap Datepicker in PHP & MySQL using Ajax</h1>


    <br><br>


    <form action="process.php" id="form">

  <div class="form-group">

    <label for="email">Date Of Birth:</label>

    <input class="date form-control" type="text" name="date-of-birth">

  </div>

  <button type="button" class="btn btn-primary" id="btnSubmit">Submit</button>

</form>

</div>


<!-- Must put our javascript files here to fast the page loading -->

<!-- jQuery library -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Popper JS -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

<!-- Bootstrap JS -->

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<!-- Bootstrap Datepicker JS -->

<script src="assets/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>

<!-- Page Script -->

<script src="assets/js/scripts.js"></script>


</body>

  

</html>

 


Script.js File

 


Next, our javascript called scripts.js from the imported the above code. Kindly check each line's comment for you to understand the process.


 


$(document).ready(function() {


// Initialize the datepicker

$('.date').datepicker({

todayHighlight: true, // to highlight the today's date

    format: 'yyyy-mm-dd', // we format the date before we will submit it to the server side

    autoclose: true //we enable autoclose so that once we click the date it will automatically close the datepicker

}); 


$("#btnSubmit").on("click", function() {

var $this     = $("#btnSubmit"); //submit button selector using ID

        var $caption        = $this.html();// We store the html content of the submit button

        var form = "#form"; //defined the #form ID

        var formData        = $(form).serializeArray(); //serialize the form into array

        var route = $(form).attr('action'); //get the route using attribute action


        // Ajax config

    $.ajax({

        type: "POST", //we are using POST method to submit the data to the server side

        url: route, // get the route value

        data: formData, // our serialized array data for server side

        beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click

            $this.attr('disabled', true).html("Processing...");

        },

        success: function (response) {//once the request successfully process to the server side it will return result here

            $this.attr('disabled', false).html($caption);

            // We will display the result using alert

            alert(response);

        },

        error: function (XMLHttpRequest, textStatus, errorThrown) {

        // You can put something here if there is an error from submitted request

        }

    });

});


 

});

 


Creating Database Table

Next, creating our database table. If you already created your database then we will continue to create our table "dob" as your table name. Here is the code below.


 


CREATE TABLE `dob` (

  `id` int(11) NOT NULL,

  `dob` date NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

 


 


Process.php File

Next, our last code to process the saving of submitted data from our from.


 


<?php

$request = $_REQUEST; //a PHP Super Global variable which used to collect data after submitting it from the form

$date = $request['date-of-birth']; //get the date of birth from collected data above


$servername = "localhost"; //set the servername

$username = "root"; //set the server username

$password = ""; // set the server password (you must put password here if your using live server)

$dbname = "demos"; // set the table name


// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection

if (!$conn) {

  die("Connection failed: " . mysqli_connect_error());

}


// Set the INSERT SQL data

$sql = "INSERT INTO dob (dob)

VALUES ('".$date."')";


// Process the query so that we will save the date of birth

if (mysqli_query($conn, $sql)) {

  echo "New record created successfully.";

} else {

  return "Error: " . $sql . "<br>" . mysqli_error($conn);

}


// Close the connection after using it

mysqli_close($conn);

?>

 

Comentarios

Entradas populares de este blog

Como proteger una api json con php al pasar el parametro POST[id] de los ataques sql injection y xss

Copia de Seguridad de Archivo MS Access (.mdb) a Pendrive con VB6

NUMEROS SERIE DE DISCO RIGIDO Y PENDRIVER USB CON PHP