PHP 8 - Product Listing

Last modified: April 02, 2022
1. Setup Jquery and Bootstrap
  • JQuery simply/make it easier to write JavaScript
  • Bootstrap, The most popular HTML, CSS, and JS library
  • Use Jquery and Bootstrap CDN
  • Use AJAX to get and insert the product
<!doctype html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> ​ <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> </head> <body> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#productModal"> Add Product </button> ​ <!-- Modal --> <form id="uploadForm" enctype="multipart/form-data"> <div class="modal fade" id="productModal" tabindex="-1" aria-labelledby="productModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="productModalLabel">Add Product</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="mb-3"> <label for="ProductName" class="form-label">Product Name</label> <input type="textbox" name="name" class="form-control" id="ProductName" placeholder="enter a product name"> </div> <div class="mb-3"> <label for="ProductPrice" class="form-label">Product Price</label> <input type="number" name="price" class="form-control" id="ProductPrice" placeholder="enter a product price"> </div> <div class="mb-3"> <label for="file" class="form-label">Product Image</label> <input type="file" class="form-control" name="file" id="file"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary submitBtn">Save changes</button> </div> </div> </div> </div> </form> <table class="tblProductList table"> <thead> <tr> <th> <b>Name</b> </th> <th> <b>Price</b> </th> <th> <b>Image</b> </th> </tr> </thead> <tbody> </tbody> </table> <script> $(document).ready(function(e){ function DrawTable(products) { $.each(products, function (i, item) { console.log(item); var $tr = $('<tr>').append( $('<td>').text(item.name), $('<td>').text(item.price), $('<td>').html("<img style='width:50px;' src='/uploads/"+ item.file_name+"' />"), ).appendTo('.tblProductList') }); } GetProduct(); function GetProduct() { $(".tblProductList").find("tr:gt(0)").remove(); $.ajax({ type: 'GET', url: 'getProducts.php', dataType: 'json', contentType: false, cache: false, processData:false, success: function(response){ DrawTable(response); } }); } $("#uploadForm").on('submit', function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: 'upload.php', data: new FormData(this), dataType: 'json', contentType: false, cache: false, processData:false, beforeSend: function(){ $('.submitBtn').attr("disabled","disabled"); }, success: function(response){ $('.message').html(''); if(response.status == 1){ alert(response.message); }else{ alert(response.message); } $(".submitBtn").removeAttr("disabled"); $('#productModal').modal('hide'); GetProduct(); } }); }); }); </script> </body> </html>
2. Login to phpMyAdmin or MySQL Workbench
create DATABASE demo; CREATE TABLE `Product` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `price` int(11) NOT NULL, `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
3 Include File
  • Create folder include in C:\xampp\htdocs
  • Create a file called dbconfig.php in include folder
  • Paste the following code, which it is used to connect the database.
<?php $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = ""; $dbName = "demo"; $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); if ($db->connect_error) { die("Connection failed: " . $db->connect_error); }
4 upload.php
  • Create a file called upload.php in C:\xampp\htdocs
<?php $uploadDir = 'uploads/'; $response = array( 'status' => 0, 'message' => 'Form submission failed, please try again.' ); // If form is submitted if(isset($_POST['name']) || isset($_POST['file']) || isset($_POST['price'])){ // Get the submitted form data $name = $_POST['name']; $price = $_POST['price']; // Check whether submitted data is not empty if(!empty($name) && !empty($price)){ $uploadStatus = 1; // Upload file $uploadedFile = ''; if(!empty($_FILES["file"]["name"])){ // File path config $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $uploadDir . $fileName; $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); // Allow certain file formats $allowTypes = array('jpg', 'png','jpeg'); if(in_array($fileType, $allowTypes)){ // Upload file to the server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ $uploadedFile = $fileName; }else{ $uploadStatus = 0; $response['message'] = 'Sorry, there was an error uploading your file.'; } }else{ $uploadStatus = 0; $response['message'] = 'Sorry, only JPG, JPEG, & PNG files are allowed to upload.'; } } if($uploadStatus == 1){ // Include the database config file include_once 'include/dbconfig.php'; // Insert form data in the database $stmt = $db->prepare("INSERT INTO product (name,file_name, price) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $name, $filename, $price); $name = $name; $filename = $uploadedFile; $insert= $stmt->execute(); $stmt->close(); $db->close(); if($insert){ $response['status'] = 1; $response['message'] = 'Form data submitted successfully!'; } } }else{ $response['message'] = 'Please fill all the mandatory fields (name, ).'; } } // Return response echo json_encode($response);
5. getProducts.php
<?php include_once 'include/dbconfig.php'; $sql = "SELECT * FROM product"; $result = $db->query($sql); $rows = array(); while($r = mysqli_fetch_assoc($result)) { $rows[] = $r; } echo json_encode($rows); ?>