Categories
PHP

Login and Registration using PHP Ajax

Learn how you can create a simple registration and login with database API.

Table structure for table `users`

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Table structure for table `serial`

CREATE TABLE `serial` (
  `serial_key` varchar(25) NOT NULL,
  `serial_value` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<?php
    class Database{ 
        private $db_host = 'localhost';
        private $db_name = 'db_login';
        private $db_username = 'root';
        private $db_password = '';
        
        public function dbConnection(){
            try{
                $conn = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name,$this->db_username,$this->db_password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            }
            catch(PDOException $e){
                echo "Connection error ".$e->getMessage(); 
                exit;
            } 
        }
    }
?>
<?php
    require 'database.php';
   
    function GetWebsiteName() {
        $db_connection = new Database();
        $conn = $db_connection->dbConnection();
        $param = "WEBSITE_NAME";
        $stmt = $conn->prepare("SELECT * FROM serial");
        $stmt->bindParam(1, $param, PDO::PARAM_STR);
        
        $stmt->execute();
        $results=$stmt->fetchAll(PDO::FETCH_ASSOC);
        $serialValue = $results[0]['serial_value'];
        return $serialValue;
    }
?>
<?php
	session_start();
	require 'database.php';
    $db_connection = new Database();
    $conn = $db_connection->dbConnection();
    $post_body = file_get_contents('php://input');
    $data = json_decode($post_body); 
    // Extract the Data Fields
    if (isset($data->username)) $username = $data->username;
    if (isset($data->password)) $password = $data->password;
    if (!isset($username)) $username = "";
    if (!isset($password)) $password = "";
    $stmt = $conn->prepare("SELECT * FROM users WHERE username = '$username' and password  = '$password'");
   
    $stmt->bindParam(1, $username, PDO::PARAM_STR);
    $stmt->bindParam(2, $password, PDO::PARAM_STR);
    $stmt->execute();
    $results=$stmt->fetchAll(PDO::FETCH_ASSOC);
    $msgResult = "Success";
    if($msgResult == "Success"){
    	$userID = $results[0]['id'];
    	$username = $results[0]['username'];
    
    	// Set Session variables
    	$_SESSION['USERID'] = $userID;
    	$_SESSION['USERNAME'] = $username;
  
    	echo "success";
    } else {
    	echo "failed";
    }
?>
<?php
	// start session
	session_start();
	// Destroy user session
	unset($_SESSION['USERID']);
	unset($_SESSION['USERNAME']);
	// Redirect to index.php page
	header("Location: ../index.php");
?>
<?php
	session_start();
	require 'database.php';
    $db_connection = new Database();
    $conn = $db_connection->dbConnection();
    $post_body = file_get_contents('php://input');
    $data = json_decode($post_body); 
    // Extract the Data Fields
    if (isset($data->username)) $username = $data->username;
    if (isset($data->password)) $password = $data->password;
    if (!isset($username)) $username = "";
    if (!isset($password)) $password = "";
    $statement = $conn->prepare("SELECT * FROM users WHERE username='$username'");
    $statement->execute();
    $results = $statement->fetchColumn();
    if ($results == 0) {
        $statement = $conn->prepare("INSERT INTO users (username, password) 
        VALUES (?, ?)");
        $statement->bindParam(1, $username, PDO::PARAM_STR);
        $statement->bindParam(2, $password, PDO::PARAM_STR);
        $statement->execute();
        echo "success";
    } else {
        echo "failed";
    }
?>
<?php 
    session_start();
    require_once('library/functions.php');
    if ((isset($_SESSION['USERID']))) {
      header("Location: home.php");
    } 
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?php echo GetWebsiteName(); ?></title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
  <link rel="stylesheet" href="./assets/css/custom.css">
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet">
</head>
<body>
  <main class="py-5 d-flex align-items-center justify-content-center h-100">
    <div class="col-lg-8 col-md-10 bg-login py-3">
      <div class="row">
        <div class="col-lg-6 column-1">
          <div class="card border-0 shadow-lg">
            <div class="card-body py-5">
              <h3 class="card-title">Login</h3>
              <p class="card-text">Dont Have an Account? <a class="reg-user" href="#"> Create your Account</a></p>
              <form id="login_form" method="post">
                <div class="form-group">
                  <input id="email" class="form-control" type="email" name="email" placeholder="Enter Username">
                </div>
                <div class="form-group">
                  <input id="password" class="form-control" type="password" name="password"
                    placeholder="Enter Password">
                </div>
                <div class="btn-wrapper text-right">
                  <button class="btn btn-primary" href="javascript:void(0)" type="submit" id="login_button">Sign
                    In</button>
                </div>
              </form>
            </div>
          </div>
        </div>
        <div class="col-lg-6 column-0" style="display:none">
          <div class="card border-0 shadow-lg">
            <div class="card-body py-5">
              <h3 class="card-title">Register Account</h3>
              <p class="card-text">Do You Have an Account? <a class="login-user" href="#"> Login</a></p>
              <form id="reg_form" method="post">
                <div class="form-group">
                  <input id="reg-email" class="form-control" type="email" name="reg-email" placeholder="Enter Username">
                </div>
                <div class="form-group">
                  <input id="reg-password" class="form-control" type="password" name="reg-password"
                    placeholder="Enter Password">
                </div>
                <div class="form-group">
                  <input id="reg-re-password" class="form-control" type="password" name="reg-re-password"
                    placeholder="Confirm Password">
                </div>
                <div class="btn-wrapper text-right">
                  <button class="btn btn-primary" href="javascript:void(0)" type="submit">Sign
                    Up</button>
                </div>
              </form>
            </div>
          </div>
        </div>
        <div class="col-lg-6 column-2 overflow-hidden">
          <div class="card border-0 bg-transparent text-right text-white">
            <img class="card-img" src="assets/images/undraw_Directions_re_kjxs.svg" alt="">
            <div class="card-img-overlay">
              <h2 class="card-title">Welcome Back</h2>
              <p class="card-text">Simply Create your account by clicking the signup button</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>
  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/izitoast/dist/js/iziToast.min.js"></script>
  <script src="./assets/js/custom.js"></script>
</body>
</html>
<?php 
  session_start();
  require_once('library/functions.php');
  if (($_SESSION['USERID'] == '') || (!isset($_SESSION['USERID']))) {
    // Redirect to index.php page
    header("Location: index.php");
  } 
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><?php echo GetWebsiteName(); ?></title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
  <link rel="stylesheet" href="./assets/css/custom.css?version:202">
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet">
</head>
<body>
  <header>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
      <a class="navbar-brand">Proghubsterzeak</a>
      <button class="navbar-toggler" data-target="#my-nav" data-toggle="collapse" aria-controls="my-nav"
        aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div id="my-nav" class="collapse navbar-collapse">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item active">
            <a class="nav-link" href="library/logout.php">Logout <span class="sr-only">(current)</span></a>
          </li>
        </ul>
      </div>
    </nav>
  </header>
  <main class="py-5 d-flex align-items-center justify-content-center h-100">
    <h1>Welcome User</h1>
  </main>
</body>
</html>
Donate to proghubsterzeak

You can make a donation to help us if you found this post helpful.

If you want to get source code, please click Download Code button on below link. For more information just leave a message/comment.

…I’m interested for Web Development Project (Shopify, WordPress, from Scratch Development) please email me at larrydaveemol@gmail.com

This simple codes will help you achieve your goals, learn and update your skills. Enjoy Coding!

Categories
JavaScript Templating PHP

Minimal Templating with Templater.js

In this application you’ll learn how display data in a table with PHP and MySQL using TemplaterJS it is a tiny JS library for minimal templating.

First we will Create the Database Table

Execute SQL Dump file

-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 17, 2020 at 08:40 AM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 7.1.27

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `db_vue_product`
--

-- --------------------------------------------------------

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `namex` varchar(255) NOT NULL,
  `category` varchar(100) NOT NULL,
  `qty` varchar(255) NOT NULL,
  `stock` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `namex`, `category`, `qty`, `stock`) VALUES
(150, '1st Product', 'category 1', '4', 'In Stock'),
(151, '2nd Product', 'category 12', '0', 'Out of stock'),
(186, '3rd Product', 'category 3', '22', 'In Stock'),
(187, '4th Products', 'wwd', '2', 'In Stock');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `products`
--
ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=188;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Creating the Connection File

After creating the table, we need to setup your database connection copy and paste the code below in order to connect to the MySQL database server. Let’s create and name it to “database.php” and put the following code inside it.

<?php
    class Database{ 
        private $db_host = 'localhost';
        private $db_name = 'db_angular_product';
        private $db_username = 'root';
        private $db_password = '';
        
        public function dbConnection(){
            try{
                $conn = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name,$this->db_username,$this->db_password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            }
            catch(PDOException $e){
                echo "Connection error ".$e->getMessage(); 
                exit;
            } 
        }
    }
?>

Web API Controller

<?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: access");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Allow-Credentials: true");
    header("Content-Type: application/json; charset=UTF-8");
    // header("Accept-Encoding", "UTF-8");

    require 'database.php';
    $db_connection = new Database();
    $conn = $db_connection->dbConnection();

    // Raw JSON Parameter
       $data=json_decode(file_get_contents("php://input"));
       
    // Extract the Data Fields
    $action = $data->action;
    switch ($action) 
    {
        case "get_product_list":
            $statement = $conn->prepare("SELECT * FROM products");
            $statement->execute();
            $results=$statement->fetchAll(PDO::FETCH_ASSOC);
            print json_encode($results, JSON_UNESCAPED_UNICODE);
            break;
          }
?>

Creating Simple Page

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
</head>

<body>

  <header>
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-text">
        <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
      </span>
    </nav>
  </header>

  <section id="my-app">
    <div class="container">
      <div class="row py-5">
        <div class="table-responsive">
          <table class="table-product table table-bordered table-striped">
            <thead class="thead-product">
              <tr>
                <th style="width:5%">No.</th>
                <th>Name</th>
                <th style="width:15%">Category</th>
                <th style="width:5%">Quantity</th>
                <th style="width:15%">Status</th>
              </tr>
            </thead>
            <tbody id="get_product">

            </tbody>
          </table>
        </div>
      </div>
    </div>
  </section>

  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/templater/templater.min.js"></script>
  <script src="./assets/js/script.js"></script>

  <script id="product_list_data" type="text/template">
    <tr>
      <td>{{ id }}</td>
      <td>{{ namex }}</td>
      <td>{{ category }}</td>
      <td>{{ qty }}</td>
      <td><span class="badge badge-default">{{ stock }}</span></td>
    </tr>
  </script>

</body>

</html>

Ajax Request function

$(document).ready(function () {
	var tmpl = $("#product_list_data").html();
	$.ajax({
		method: "POST",
		url: "./library/api.php",
		dataType: 'json',
		contentType: 'application/json',
		data: JSON.stringify({ "action": "get_product_list" }),
		success: function (prodData) {
			$.each(prodData, function (i, product) {
				const template = templater(tmpl);
				$('#get_product').append(template(product));
			});
		}
	});
})

Download the complete source code. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!

Categories
JavaScript Templating PHP VueJS

VueJS PHP CRUD using Web API

I would like to share my CRUD (Create, Read, Update and Delete) using Web API and VueJS in PHP.

Creating the Database Table

Execute SQL Dump file

-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 17, 2020 at 08:40 AM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 7.1.27

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `db_vue_product`
--

-- --------------------------------------------------------

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `namex` varchar(255) NOT NULL,
  `category` varchar(100) NOT NULL,
  `qty` varchar(255) NOT NULL,
  `stock` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `namex`, `category`, `qty`, `stock`) VALUES
(150, '1st Product', 'category 1', '4', 'In Stock'),
(151, '2nd Product', 'category 12', '0', 'Out of stock'),
(186, '3rd Product', 'category 3', '22', 'In Stock'),
(187, '4th Products', 'wwd', '2', 'In Stock');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `products`
--
ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=188;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Creating the Connection File

<?php
    class Database{ 
        private $db_host = 'localhost';
        private $db_name = 'db_vue_product';
        private $db_username = 'root';
        private $db_password = '';
        
        public function dbConnection(){
            try{
                $conn = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name,$this->db_username,$this->db_password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            }
            catch(PDOException $e){
                echo "Connection error ".$e->getMessage(); 
                exit;
            } 
        }
    }
?>

Web API Controller

The Web API Controller consists of the following three Action methods.
– Get all the records from the Product table
– Add and Update Product
– Delete Product

<?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: access");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Allow-Credentials: true");
    header("Content-Type: application/json; charset=UTF-8");
    // header("Accept-Encoding", "UTF-8");

    require 'database.php';
    $db_connection = new Database();
    $conn = $db_connection->dbConnection();

    // Raw JSON Parameter
       $data=json_decode(file_get_contents("php://input"));
       
    // Extract the Data Fields
    $action = $data->action;
    switch ($action) 
    {
        case "get_product_list":

            $statement = $conn->prepare("SELECT * FROM products");
            $statement->execute();
            $results=$statement->fetchAll(PDO::FETCH_ASSOC);
            print json_encode($results, JSON_UNESCAPED_UNICODE);
            break;

        case "AddUpdate":
          
            $id = $data->id;
            $name = $data->name;
            $category = $data->category;
            $qty = $data->qty;
            $action = $data->btnName;
            
            if($qty > 0) {
              $qty_status = 'In Stock';
            } else if($qty < 1) {
              $qty_status = 'Out of stock';
            }

            if ($action =='SAVE') {
                  $statement = $conn->prepare("SELECT * FROM products WHERE id='$id'");
                  $statement->execute();
                  $results=$statement->fetchAll(PDO::FETCH_ASSOC);
                  if ($results > 1) {
                    $statement = $conn->prepare("INSERT INTO products (id, namex, category, qty, stock) 
                    VALUES ('', ?, ?, ?, ?)");
                    $statement->bindParam(1, $name, PDO::PARAM_STR);
                    $statement->bindParam(2, $category, PDO::PARAM_STR);
                    $statement->bindParam(3, $qty, PDO::PARAM_STR);
                    $statement->bindParam(4,$qty_status);
                    $statement->execute();
                   
                  } else {
                  }
  
            } else if ($action =='UPDATE') {
                  $id = $data->id;
                  $statement = $conn->prepare("SELECT * FROM products WHERE id='$id'");
                  $statement->execute();
                  $results=$statement->fetchAll(PDO::FETCH_ASSOC);
                  if ($results > 1) {
                    $statement = $conn->prepare("UPDATE products SET namex=?, category=?, qty=?, stock=? WHERE id=$id");
                    $statement->bindParam(1, $name, PDO::PARAM_STR);
                    $statement->bindParam(2, $category, PDO::PARAM_STR);
                    $statement->bindParam(3, $qty, PDO::PARAM_STR);
                    $statement->bindParam(4,$qty_status);
                    $statement->execute();
                  } else {
                  }
            }
            break;

        case "Delete":
        
            $id=$data->id;

            $statement =$conn->prepare("DELETE FROM products WHERE id = '$id'");
            $statement->execute();
            break;
    }
?>

Creating a Vue instance with the Vue function

const app = new Vue({
	el: "#my-app",
	data: {
		errors: [],
		searchQuery: '',
		products: [],
		id: "",
		name: null,
		category: null,
		qty: null,
		btnName: "SAVE",
		formTitle: "ADD PRODUCT"
	},
	methods: {

		addProduct: function () {
			this.id = "";
			this.name = "";
			this.category = "";
			this.qty = "";
			this.btnName = "SAVE";
			this.formTitle = 'ADD PRODUCT';
		},

		getAllProduct: function () {
			var self = this;
			axios({
				method: "POST",
				url: "./library/api.php",
				dataType: 'json',
				contentType: 'application/json',
				data: JSON.stringify({ "action": "get_product_list" }),
			}).then(function success(response) {
				self.products = response.data
			});
		},

		deleteProduct: function (id) {
			var self = this;
			if (confirm("Are you sure you want to remove it?")) {
				axios({
					method: "POST",
					url: "./library/api.php",
					data: { 'id': id, 'action': 'Delete' }
				}).then(function success(response) {
					self.getAllProduct();
					let message = "Product was successfully deleted";
					self.flashMessage(message, 'success');
				});
			}
		},

		update_data: function (id, name, category, qty) {
			this.id = id;
			this.name = name;
			this.category = category;
			this.qty = qty;
			this.btnName = "UPDATE";
			this.formTitle = 'EDIT PRODUCT';
		},

		InsertUpdateProduct: function (event) {
			var self = this;

			if (this.name === '' || this.category === '' || this.qty === '') {
				this.errors = [];
				if (!this.name) this.errors.push("Product Name required.");
				if (!this.category) this.errors.push("Category required.");
				if (!this.qty) this.errors.push("Quantity required.");
			} else {
				axios({
					method: "POST",
					url: "./library/api.php",
					dataType: 'json',
					contentType: 'application/json',
					data: JSON.stringify({ id: this.id, name: this.name, category: this.category, qty: this.qty, btnName: this.btnName, "action": "AddUpdate" }),
				}).then(function success(response) {
					$('#Productform').modal('hide');
					self.errors.splice(0);
					this.name = "";
					this.category = "";
					this.qty = "";
					this.id = "";
					self.getAllProduct();
					if (self.btnName == 'SAVE') {
						let message = "Product was successfully Added";
						self.flashMessage(message, 'success');
					} else if (self.btnName == 'UPDATE') {
						let message = "Product was successfully Updated";
						self.flashMessage(message, 'success');
					}
				});
			}
		},

		filterItems: function (products) {
			var self = this;
			return products.filter(function (product) {
				let regex = new RegExp('(' + self.searchQuery + ')', 'i');
				return product.namex.match(regex);
			})
		},

		flashMessage: function (message, type = 'success') {
			if (type === 'success') {
				iziToast.success({
					title: 'Success :',
					message: message.charAt(0).toUpperCase() + message.substr(1).toLowerCase(),
					timeout: 4000,
					// theme: 'dark',
					animateInside: true,
					position: 'topRight',
					icon: 'fa fa-heart'
				});
			} else if (type === 'error') {
				iziToast.error({
					title: 'Error :',
					message: message.charAt(0).toUpperCase() + message.substr(1).toLowerCase(),
					timeout: 4000,
					// theme: 'dark',
					animateInside: true,
					position: 'topRight',
				});
			} else if (type === 'info') {
				iziToast.info({
					title: 'Info :',
					message: message.charAt(0).toUpperCase() + message.substr(1).toLowerCase(),
					timeout: 4000,
					// theme: 'dark',
					animateInside: true,
					position: 'topRight',
				});
			} else {
				iziToast.warning({
					title: 'Success :',
					message: message.charAt(0).toUpperCase() + message.substr(1).toLowerCase(),
					timeout: 4000,
					// theme: 'dark',
					animateInside: true,
					position: 'topRight',
				});
			}
		},

	},
	mounted() {
		this.getAllProduct();
	},
});

Creating Product Page

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/izitoast.min.css">
  <style>
  .warning {
    background-color: rgb(255, 140, 0);
    color: #fff;
  }
  </style>
</head>

<body>

  <header>
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-text">
        <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
      </span>
    </nav>
  </header>

  <section id="my-app">
    <div class="container">
      <div class="row my-5">
        <button v-on:click="addProduct();" type="button" class="btn btn-info btn-sm" data-toggle="modal"
          data-target="#Productform">Add
          Product</button>
        <div class="ml-auto">
          <input class="form-control ng-pristine ng-valid" v-model="searchQuery" type="text">
        </div>
      </div>
      <div class="row">
        <div class="table-responsive">
          <table class="table-product table table-bordered table-striped">
            <thead class="thead-product">
              <tr>
                <th style="width:5%">No.</th>
                <th>Name</th>
                <th style="width:15%">Category</th>
                <th style="width:5%">Quantity</th>
                <th style="width:15%">Status</th>
                <th style="width:18%">Action</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(product, index) in filterItems(products)" :key="product.id">
                <td>{{ product.id }}</td>
                <td>{{ product.namex }}</td>
                <td>{{ product.category }}</td>
                <td>{{ product.qty }}</td>
                <td v-if="product.qty > 10"><span class="badge badge-success">In Stock</span></td>
                <td v-else-if="product.qty <= 10 && product.qty > 0"><span class="badge badge-primary">ALmost Sold
                    Out</span></p>
                <td v-else><span class="badge badge-warning">Out Of Stock</span></td>
                <td>
                  <div class=" buttons text-center">
                    <button v-on:click="update_data(product.id, product.namex, product.category, product.qty);"
                      class="btn btn-primary btn-edit btn-sm" type="button" data-toggle="modal"
                      data-target="#Productform">Edit</button>
                    <button v-on:click="deleteProduct(product.id);"
                      class="btn btn-danger btn-delete btn-sm">Delete</button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <div id="Productform" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title"
      aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header bg-light">
            <h5 class="modal-title" id="my-modal-title">{{ formTitle }}</h5>
            <button class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <p v-if="errors.length" class="col-12">
            <b>Please correct the following error(s):</b>
            <ul>
              <li v-for="error in errors">{{ error }}</li>
            </ul>
          </p>
          <div class="modal-body">
            <form @submit.stop.prevent="submit">
              <input type="hidden" ng-model="id">
              <div class="form-group">
                <label for="my-input">Product</label>
                <input class="form-control" type="text" v-model="name" placeholder="Product Name" />
              </div>
              <div class="form-group">
                <label for="my-input">Category</label>
                <input class="form-control" type="text" v-model="category" placeholder="Category" />
              </div>
              <div class="form-group">
                <label for="my-input">Quantity</label>
                <input class="form-control" type="number" v-model="qty" placeholder="Quantity" required />
              </div>
              <input name="insert" type="submit" class="btn btn-primary btn-add my-2" v-on:click="InsertUpdateProduct()"
                :value="btnName" />
            </form>
          </div>
        </div>
      </div>
    </div>
  </section>

  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/bootstrap/js/bootstrap.bundle.js"></script>
  <script src="./assets/izitoast/dist/js/izitoast.min.js"></script>
  <script src="./assets/vue/vue.js"></script>
  <script src="./assets/vue/axios.js"></script>
  <script src="./assets/js/script.js"></script>

</body>

</html>

If you want to get complete source code, please click Download Code button on below link. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!

Categories
AngularJS JavaScript Templating PHP

AngularJS PHP CRUD using Web API

I would like to share my CRUD (Create, Read, Update and Delete) using Web API and AngularJS in PHP.

Creating the Database Table

Execute SQL Dump file

-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 17, 2020 at 08:40 AM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 7.1.27

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `db_angular_product`
--

-- --------------------------------------------------------

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `namex` varchar(255) NOT NULL,
  `category` varchar(100) NOT NULL,
  `qty` varchar(255) NOT NULL,
  `stock` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `namex`, `category`, `qty`, `stock`) VALUES
(150, '1st Product', 'category 1', '4', 'In Stock'),
(151, '2nd Product', 'category 12', '0', 'Out of stock'),
(186, '3rd Product', 'category 3', '22', 'In Stock'),
(187, '4th Products', 'wwd', '2', 'In Stock');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `products`
--
ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=188;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Creating the Connection File

<?php
    class Database{ 
        private $db_host = 'localhost';
        private $db_name = 'db_angular_product';
        private $db_username = 'root';
        private $db_password = '';
        
        public function dbConnection(){
            try{
                $conn = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name,$this->db_username,$this->db_password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            }
            catch(PDOException $e){
                echo "Connection error ".$e->getMessage(); 
                exit;
            } 
        }
    }
?>

Web API Controller

The Web API Controller consists of the following three Action methods.
– Get all the records from the Product table
– Add and Update Product
– Delete Product

<?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: access");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Allow-Credentials: true");
    header("Content-Type: application/json; charset=UTF-8");
    // header("Accept-Encoding", "UTF-8");

    require 'database.php';
    $db_connection = new Database();
    $conn = $db_connection->dbConnection();

    // Raw JSON Parameter
       $data=json_decode(file_get_contents("php://input"));
       
    // Extract the Data Fields
    $action = $data->action;
    switch ($action) 
    {
        case "get_product_list":

            $statement = $conn->prepare("SELECT * FROM products");
            $statement->execute();
            $results=$statement->fetchAll(PDO::FETCH_ASSOC);
            print json_encode($results, JSON_UNESCAPED_UNICODE);
            break;

        case "AddUpdate":
          
            $name = $data->name;
            $category = $data->category;
            $qty = $data->qty;
            $action = $data->btnName;
            
            if($qty > 0) {
              $qty_status = 'In Stock';
            } else if($qty < 1) {
              $qty_status = 'Out of stock';
            }

            if ($action =='SAVE') {
                  $statement = $conn->prepare("SELECT * FROM products WHERE namex='$name'");
                  $statement->execute();
                  $results=$statement->fetchAll(PDO::FETCH_ASSOC);
                  if ($results > 1) {
                    $statement = $conn->prepare("INSERT INTO products (id, namex, category, qty, stock) 
                    VALUES ('', ?, ?, ?, ?)");
                    $statement->bindParam(1, $name, PDO::PARAM_STR);
                    $statement->bindParam(2, $category, PDO::PARAM_STR);
                    $statement->bindParam(3, $qty, PDO::PARAM_STR);
                    $statement->bindParam(4,$qty_status);
                    $statement->execute();
                   
                  } else {
                  }
  
            } else if ($action =='UPDATE') {
                  $id = $data->id;
                  $statement = $conn->prepare("SELECT * FROM products WHERE namex='$name'");
                  $statement->execute();
                  $results=$statement->fetchAll(PDO::FETCH_ASSOC);
                  if ($results > 1) {
                    $statement = $conn->prepare("UPDATE products SET namex=?, category=?, qty=?, stock=? WHERE id=$id");
                    $statement->bindParam(1, $name, PDO::PARAM_STR);
                    $statement->bindParam(2, $category, PDO::PARAM_STR);
                    $statement->bindParam(3, $qty, PDO::PARAM_STR);
                    $statement->bindParam(4,$qty_status);
                    $statement->execute();
                  } else {
                  }
            }
            break;

        case "Delete":
        
            $name=$data->name;

            $statement =$conn->prepare("DELETE FROM products WHERE namex = '$name'");
            $statement->execute();
            break;
    }
?>

Angular Javascript code for register module and create controller.

var app = angular.module("Module_Product", [])

	.controller("Controller_Product", function ($scope, $http, ) {

		/* Load Product*/
		$scope.fetchData = function () {
			$http({
				method: "POST",
				url: "./library/api.php",
				dataType: 'json',
				contentType: 'application/json',
				data: JSON.stringify({ "action": "get_product_list" }),
			}).then(function success(response) {
				$scope.products = response.data;
			});
		};


		/* Insert/Update Product */
		$scope.addData = function () {
			$scope.btnName = "SAVE";
			$scope.formTitle = 'ADD PRODUCT';
			$scope.name = "";
			$scope.category = "";
			$scope.qty = "";
			$scope.stock = "";
		}

		$scope.update_data = function (id, name, category, qty, btnName) {
			$scope.id = id;
			$scope.name = name;
			$scope.category = category;
			$scope.qty = qty;
			$scope.btnName = "UPDATE";
			$scope.formTitle = 'EDIT PRODUCT';
		}

		$scope.InsertUpdateData = function () {
			if ($scope.name == null || $scope.category == null || $scope.qty == null) {
				alert("Please complete the required fields");
			} else {
				$http({
					method: "POST",
					url: "./library/api.php",
					dataType: 'json',
					contentType: 'application/json',
					data: JSON.stringify({ id: $scope.id, name: $scope.name, category: $scope.category, qty: $scope.qty, stock: $scope.stock, btnName: $scope.btnName, "action": "AddUpdate" }),
				}).then(function success(response) {
					$scope.name = "";
					$scope.category = "";
					$scope.qty = "";
					$scope.stock = "";
					$scope.fetchData();
					if ($scope.btnName == 'SAVE') {
						let message = "Product was successfully Added";
						$scope.flashMessage(message, 'success');
					} else if ($scope.btnName == 'UPDATE') {
						let message = "Product was successfully Updated";
						$scope.flashMessage(message, 'success');
					}
				});
			}
		}

		/* Delete Data*/
		$scope.deleteProduct = function (name) {
			if (confirm("Are you sure you want to remove it?")) {
				$http({
					method: "POST",
					url: "./library/api.php",
					data: { 'name': name, 'action': 'Delete' }
				}).then(function success(response) {
					$scope.success = true;
					$scope.error = false;
					$scope.fetchData();
					let message = "Product was successfully deleted";
					$scope.flashMessage(message, 'success');
				});

			}
		}

		/*Flash Message*/
		$scope.flashMessage = function (message, type = 'success') {
			if (type === 'success') {
				iziToast.success({
					title: 'Success :',
					message: message.charAt(0).toUpperCase() + message.substr(1).toLowerCase(),
					timeout: 4000,
					// theme: 'dark',
					animateInside: true,
					position: 'topRight',
					icon: 'fa fa-heart'
				});
			} else if (type === 'error') {
				iziToast.error({
					title: 'Error :',
					message: message.charAt(0).toUpperCase() + message.substr(1).toLowerCase(),
					timeout: 4000,
					// theme: 'dark',
					animateInside: true,
					position: 'topRight',
				});
			} else if (type === 'info') {
				iziToast.info({
					title: 'Info :',
					message: message.charAt(0).toUpperCase() + message.substr(1).toLowerCase(),
					timeout: 4000,
					// theme: 'dark',
					animateInside: true,
					position: 'topRight',
				});
			} else {
				iziToast.warning({
					title: 'Success :',
					message: message.charAt(0).toUpperCase() + message.substr(1).toLowerCase(),
					timeout: 4000,
					// theme: 'dark',
					animateInside: true,
					position: 'topRight',
				});
			}
		}

	});

Creating Product Page

<!DOCTYPE html>
<html lang="en" ng-app="Module_Product">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/izitoast.min.css">
  <style>
  .warning {
    background-color: rgb(255, 140, 0);
    color: #fff;
  }
  </style>
</head>

<body ng-controller="Controller_Product">

  <header>
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-text">
        <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
      </span>
    </nav>
  </header>

  <section>
    <div class="container" ng-init="fetchData()">
      <div class="row my-5">
        <button ng-click="addData();" type="button" class="btn btn-info btn-sm" data-toggle="modal"
          data-target="#Productform">Add Product</button>
        <div class="ml-auto">
          <input class="form-control ng-pristine ng-valid" ng-model="searchKeyword" type="text">
        </div>
      </div>
      <div class="row">
        <div class="table-responsive">
          <table class="table-product table table-bordered table-striped">
            <thead class="thead-product">
              <tr>
                <th style="width:5%">No.</th>
                <th>Name</th>
                <th style="width:15%">Category</th>
                <th style="width:5%">Quantity</th>
                <th style="width:15%">Status</th>
                <th style="width:18%">Action</th>
              </tr>
            </thead>
            <tbody>
              <tr ng-repeat="product in products | filter: searchKeyword">
                <!-- <tr ng-repeat="product in products track by $index"> -->
                <td>{{$index+1}}</td>
                <td>{{product.namex}}</td>
                <td>{{product.category}}</td>
                <td>{{product.qty}}</td>
                <td><span class="badge badge-primary" ng-class="{warning: product.qty < 1}"> {{product.stock}}</span>
                </td>
                <td>
                  <div class=" buttons text-center">
                    <button class="btn btn-primary btn-edit btn-sm"
                      ng-click="update_data(product.id, product.namex, product.category, product.qty)" type="button"
                      class="btn btn-info btn-sm" data-toggle="modal" data-target="#Productform">Edit</button>
                    <button class="btn btn-danger btn-delete btn-sm"
                      ng-click="deleteProduct(product.namex);">Delete</button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </section>

  <div id="Productform" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header bg-light">
          <h5 class="modal-title" id="my-modal-title">{{formTitle}}</h5>
          <button class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form>
            <input type="hidden" ng-model="id">
            <div class="form-group">
              <label for="my-input">Product</label>
              <input class="form-control" type="text" ng-model="name" placeholder="Product Name" />
            </div>
            <div class="form-group">
              <label for="my-input">Category</label>
              <input class="form-control" type="text" ng-model="category" placeholder="Category" />
            </div>
            <div class="form-group">
              <label for="my-input">Quantity</label>
              <input class="form-control" type="text" ng-model="qty" placeholder="Quantity" />
            </div>
            <input data-dismiss="modal" name="insert" type="submit" class="btn btn-primary btn-add my-2"
              ng-click="InsertUpdateData()" value="{{btnName}}" />
          </form>
        </div>
      </div>
    </div>
  </div>

  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/bootstrap/js/bootstrap.bundle.js"></script>
  <script src="./assets/izitoast/dist/js/izitoast.min.js"></script>
  <script src="./assets/angular/angular.min.js"></script>
  <script src="./assets/js/script.js"></script>
</body>

</html>

If you want to get complete source code, please click Download Code button on below link. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!

Categories
PHP

Login with ajax and jQuery

This is a simple login page that use AJAX to create a user-friendly application.

Creating the Database Table

Execute SQL Dump file

-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 13, 2020 at 12:00 PM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 7.1.27

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `db_login`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_users`
--

CREATE TABLE `tbl_users` (
  `user_id` int(11) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `isadmin` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_users`
--

INSERT INTO `tbl_users` (`user_id`, `email`, `password`, `isadmin`) VALUES
(1, 'gr@gmail.com', 'admin', '1'),
(2, 'dddd', 'dsadasdddd', ''),
(3, 'ddd', 'ddd', '');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_users`
--
ALTER TABLE `tbl_users`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_users`
--
ALTER TABLE `tbl_users`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Creating the Connection File

After creating the table, we need to setup your database connection copy and paste the code below in order to connect to the MySQL database server. Let’s create and name it to “db_conn.php” and put the following code inside it.

<?php 
session_start();

$conn=mysqli_connect("localhost", "root", "", "db_login");

if(!$conn){
    die("Error: Failed To Connect Database!");
}
?>

Creating Login Page

First we will prevent user not to redirecting to home page if they are not logging in. We’ve two input box username and password for entering value and we can use AJAX for the submit button with jQuery. We can also use bootstrap for enhancing layout design and Izitoast for awesome looking popups Notification.

<?php
include "db_con.php";

if(isset($_SESSION['USERNAME'])) {
     header("Location: home.php"); // redirects them to homepage
     exit;
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
  <style>
  footer {
    position: absolute;
    width: 100%;
    bottom: 0;
  }
  </style>
</head>

<body class="login" style="height: 100vh;">
  <header>
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-text">
        <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
      </span>
    </nav>
  </header>
  <main class="py-5">
    <section>
      <div class="col-lg-4 col-md-4 mx-auto mt-5">
        <form id="loginform" method="post">
          <div class="form-group">
            <label for="my-username">Username</label>
            <input id="username" class="form-control" type="text" name="username">
          </div>
          <div class="form-group">
            <label for="my-password">Username</label>
            <input id="password" class="form-control" type="password" name="password">
          </div>
          <button type="submit" class="btn btn-primary btn-block">LOGIN</button>
        </form>
      </div>
    </section>
  </main>
  <footer class="text-center py-2 bg-light">
    © 2020 Your Site
  </footer>
  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/izitoast/dist/js/iziToast.min.js"></script>
  <script src="./assets/js/custom.js"></script>
</body>

</html>

Creating jQuery AJAX

AJAX will send request it will pass entered username and password as data. If the user entered valid password and username the response is equal to “success” and redirect to home.php page otherwise show an error message notification.

$(document).on('submit', '#loginform', function (event) {
  event.preventDefault();

  var username = $("#username").val();
  var password = $("#password").val();
  if (username != "" && password != "") {
    $.ajax({
      url: 'login.php',
      type: 'POST',
      data: {
        do_login: "login",
        username: username,
        password: password,
      },
      success: function (response) {

        if (response == "success") {
          iziToast.success({
            title: 'Success',
            message: 'Successfully Login',
            pauseOnHover: true,
            position: 'topRight',
            animateInside: true
          });

          window.location.href = "home.php";
        }
        else {
          iziToast.error({
            title: 'Error',
            message: 'Invalid Email or Password',
            pauseOnHover: true,
            position: 'topRight',
            animateInside: true
          });
        }
      }
    });

  } else {
    iziToast.info({
      title: 'Info',
      message: 'Please Fill All The Details',
      pauseOnHover: true,
      position: 'topRight',
      animateInside: true,
    });
  }

  return false;
});

Check if the users exists in the database table

<?php
  require_once 'db_con.php';
  
  if (isset($_POST['do_login'])){
    $email = $_POST['username'];
    $password = $_POST['password'];

    $query = mysqli_query($conn,"SELECT * FROM `tbl_users` WHERE `email` = '$email' && `password` = '$password'");
    $row = mysqli_num_rows($query);
    $fetch = mysqli_fetch_array($query);

  if($row > 0){
    $uname = $row['email'];
    $_SESSION['USERNAME'] = $uname;
    echo "success";
  }else{
    echo "failed";
  }
  
  }
?>

Create home.php and we’ll prevent user from coming back to login if they are already logged in. Logout button to end user’s session.

<?php 
include('db_con.php');

//Check whether the session variable SESS_MEMBER_ID is present or not
if (!isset($_SESSION['USERNAME']) || (trim($_SESSION['USERNAME']) == '')) {
    header("location: index.php");
    exit();
}

// logout
if(isset($_POST['logout'])){
    session_destroy();
    header('Location: index.php');
}
 ?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
  <style>
  footer {
    position: absolute;
    width: 100%;
    bottom: 0;
  }
  </style>
</head>

<body>
  <header>
    <nav class="navbar navbar-light bg-light"><span class="navbar-text">
        <a href="https://proghubsterzeak.com/">https://proghubsterzeak.com</a>
      </span></nav>
  </header>
  <main class="py-5">
    <section>
      <div class="col-lg-4 col-md-4 mx-auto mt-5 text-center">
        <h3>Welcome: <?php echo  $_SESSION['USERNAME']; ?> </h3>
        <p class="text-center">Congratulations ! You've been logged in successfully</p>
        <form action="" method="post">
          <button name="logout" type="submit" class="mt-5 btn btn-primary btn-block">LOGOUT</button>
        </form>
      </div>
    </section>
  </main>
  <footer class="text-center py-2 bg-light">© 2020 Your Site </footer>
</body>

</html>

Download the complete source code. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!

Categories
JavaScript Templating PHP

Ajax request with Handlebars.js

In this application you’ll learn how use Handlebars.js to render template and display data in a table with PHP and MySQL.

First get the latest file for handlebars here https://www.npmjs.com/package/handlebars

Creating the Database Table

Execute SQL Dump file

-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 12, 2020 at 01:28 PM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 7.1.27

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `db_product`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_products`
--

CREATE TABLE `tbl_products` (
  `id` int(11) NOT NULL,
  `name` varchar(200) NOT NULL,
  `sku` varchar(100) NOT NULL,
  `price` varchar(50) NOT NULL,
  `qty` varchar(50) NOT NULL,
  `description` text NOT NULL,
  `availability` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_products`
--

INSERT INTO `tbl_products` (`id`, `name`, `sku`, `price`, `qty`, `description`, `availability`) VALUES
(4, 'Second Item', 'sku-1234', '2000', '456', 'Loerem ipsum ', '120'),
(48, 'First Item', 'sku-122', '20', '1000', 'lorem ipsumssss', '0'),
(49, 'Third item', 'sku-55', '800', '6', 'Sana All', '20');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_products`
--
ALTER TABLE `tbl_products`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `id` (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_products`
--
ALTER TABLE `tbl_products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=50;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Creating the Connection File

After creating the table, we need to setup your database connection copy and paste the code below in order to connect to the MySQL database server. Let’s create and name it to “db_conn.php” and put the following code inside it.

<?php 
    $conn=mysqli_connect("localhost", "root", "", "db_product");

        if(!$conn){
            die("Error: Failed To Connect Database!");
        }
?>

Creating Simple Page

First we will create simple page for our application it contains a script template to display records in a table from the “tbl_products” database table. Copy and paste the code below

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/bootstrap.min.css">
  <style>
  footer {
    position: absolute;
    width: 100%;
    bottom: 0;
  }
  </style>
</head>

<body>
  <header>
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-text">
        <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
      </span>
    </nav>
  </header>
  <main class="py-5">
    <script id="product_list_data" type="text/template">
      <tr>
        <td>{{id}}</td>
        <td>{{name}}</td>
        <td>{{sku}}</td>
        <td>{{price}}</td>
        <td>{{qty}}</td>
        <td>{{description}}</td>
        <td>{{availability}}</td>
      </tr>
  </script>

    <section>
      <div class="container">
        <table class="table">
          <table id='load-data' class='table table-striped table-bordered' style='width:100%'>
            <thead class="thead-dark">
              <tr>
                <th>#</th>
                <th>Product Name</th>
                <th>SKU</th>
                <th>Amount</th>
                <th>Quantity</th>
                <th>Description</th>
                <th>Availability</th>
              </tr>
            </thead>
            <tbody id="get_product">
            </tbody>
          </table>
        </table>
      </div>
    </section>
  </main>
  <footer class="text-center py-2 bg-light">
    © 2020 Your Site
  </footer>
  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/handlebars/handlebars.min.js"></script>
  <script src="./assets/js/render.js"></script>
</body>

</html>

ajax request

$(document).ready(function () {
  var template = $("#product_list_data").html();
  $.ajax({
    url: 'product_list.php',
    dataType: "json",
    success: function (prodData) {

      $.each(prodData, function (i, product) {
        var html = Handlebars.compile(template);
        $('#get_product').append(html(product));
      });

    }
  });
})

Copy and paste the code below and save it as product_list.php. This code will simply retrieve the records from the “tbl_products” table from database and it will return as JSON.

<?php
	require_once 'db_con.php';
	$bacth = array();

	$queryretrieve=mysqli_query($conn,"SELECT * FROM tbl_products");
	$n = mysqli_num_rows($queryretrieve);

	if ($n!=0) {
		while($result = mysqli_fetch_array($queryretrieve)){
			$bacth[] = $result;
	} 
	echo json_encode($bacth);
	}
?>

Download the complete source code. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!

Categories
JavaScript Templating PHP

Ajax request with Mustache.js

In this application you’ll learn how use mustache.js to render mustache template and display data in a table with PHP and MySQL.

Creating the Database Table

Execute SQL Dump file

-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 12, 2020 at 01:28 PM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 7.1.27

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `db_product`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_products`
--

CREATE TABLE `tbl_products` (
  `id` int(11) NOT NULL,
  `name` varchar(200) NOT NULL,
  `sku` varchar(100) NOT NULL,
  `price` varchar(50) NOT NULL,
  `qty` varchar(50) NOT NULL,
  `description` text NOT NULL,
  `availability` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_products`
--

INSERT INTO `tbl_products` (`id`, `name`, `sku`, `price`, `qty`, `description`, `availability`) VALUES
(4, 'Second Item', 'sku-1234', '2000', '456', 'Loerem ipsum ', '120'),
(48, 'First Item', 'sku-122', '20', '1000', 'lorem ipsumssss', '0'),
(49, 'Third item', 'sku-55', '800', '6', 'Sana All', '20');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_products`
--
ALTER TABLE `tbl_products`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `id` (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_products`
--
ALTER TABLE `tbl_products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=50;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Creating the Connection File

After creating the table, we need to setup your database connection copy and paste the code below in order to connect to the MySQL database server. Let’s create and name it to “db_conn.php” and put the following code inside it.

<?php 
    $conn=mysqli_connect("localhost", "root", "", "db_product");

        if(!$conn){
            die("Error: Failed To Connect Database!");
        }
?>

Creating Simple Page

First we will create simple page for our application it contains a data table showing the records from the “tbl_products” database table. We’ll include mustache Autoloader it require mustache to render our templates.

 <?php 
include('src/mustache/Autoloader.php');
Mustache_Autoloader::register();
$entry = new Mustache_Engine;
$product_list_template = file_get_contents('template/product_list.mustache');
?>

 <!DOCTYPE html>
 <html lang="en">

 <head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Proghubsterzeak</title>
   <link rel="stylesheet" href="./assets/bootstrap/bootstrap.min.css">
   <style>
   footer {
     position: absolute;
     width: 100%;
     bottom: 0;
   }
   </style>
 </head>

 <body>
   <header>
     <nav class="navbar navbar-light bg-light">
       <span class="navbar-text">
         <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
       </span>
     </nav>
   </header>
   <main class="py-5">
     <section>
       <div class="container">
         <table class="table">
           <table id='load-data' class='table table-striped table-bordered' style='width:100%'>
             <thead class="thead-dark">
               <tr>
                 <th>#</th>
                 <th>Product Name</th>
                 <th>SKU</th>
                 <th>Amount</th>
                 <th>Quantity</th>
                 <th>Description</th>
                 <th>Availability</th>
               </tr>
             </thead>
             <tbody id="get_product">

             </tbody>
           </table>

           <?php echo $entry->render($product_list_template); ?>
         </table>
       </div>
     </section>
   </main>
   <footer class="text-center py-2 bg-light">
     © 2020 Your Site
   </footer>
   <script src="./assets/jquery/jquery.min.js"></script>
   <script src="./assets/mustache/js/mustache.min.js"></script>
   <script src="./assets/js/render.js"></script>
 </body>

 </html>

This is a shorthand Ajax function

$(document).ready(function () {
  var template = $("#product_list_data").html();
  $(function () {
    $.getJSON('product_list.php',
      function (prodData) {

        $.each(prodData, function (i, product) {
          var html = Mustache.render(template, product);
          $('#get_product').append(html);
        });

      });
  });
})

which is equal to

$(document).ready(function () {
  var template = $("#product_list_data").html();
  $.ajax({
    url: 'product_list.php',
    dataType: "json",
    success: function (prodData) {

      $.each(prodData, function (i, product) {
        var html = Mustache.render(template, product);
        $('#get_product').append(html);
      });

    }
  });
})

Copy and paste the code below and save it as product_list.php. This code will simply retrieve the records from the “tbl_products” table from database and it will return to JSON.

<?php
	require_once 'db_con.php';
	$bacth = array();

	$queryretrieve=mysqli_query($conn,"SELECT * FROM tbl_products");
	$n = mysqli_num_rows($queryretrieve);

	if ($n!=0) {
		while($result = mysqli_fetch_array($queryretrieve)){
			$bacth[] = $result;
	} 
	echo json_encode($bacth);
	}
?>

Download the complete source code. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!

Categories
PHP

Display Blob image in MySQL using PHP

In this simple program read MySQL BLOB using PHP . This a user-friendly program, start learning with this basic application, or feel free to modify the codes. I hope you’ll customize this codes according to your individual project’s needs .

Getting Started:

Get the source file i used it for enhancing layout design, Bootstrap can be found in this link https://getbootstrap.com/

Copy the code below and paste it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="./css/bootstrap.css">
</head>
<style>
.cont-wrapper li img {
max-width: 100px;
height: 100px;
width: 100%;
object-fit: cover;
margin: 5px;
border: 2px solid #d55656;
border-radius: 5px;
}
.cont-wrapper li a {
    margin: 10px;
    color: #ccc;
    width: 100%;
transition: all .3s ease-in-out;
-webkit-transition: all .3s ease-in-out;
padding: 16px 0;
}
.cont-wrapper li a:hover {
color: #d55656;
text-decoration: none;
}
.col-list {
background-color: #000c;
}
.cont-wrapper li {
list-style: none;
border-top: 1px solid #ccc;
border-left: none;
border-right: none;
}
.cont-wrapper li:hover img {
    opacity: 0.8;
}
.cont-wrapper li:first-child  {
  border-top: none;
}
.cont-wrapper li:last-child  {
  border-bottom: none;
}

.cont-wrapper {
padding: 0;
}

@media screen and (max-width: 440px ) {
.cont-wrapper li img {
    max-width: 70px;
    height: 70px;
}
}
</style>
<body>
    <div class="myapp">
        <div class="container-fluid">
              <div class="row">
                <div class="col-list col-md-12 col-sm-6 mb-3">
                  <ul class="cont-wrapper mt-3">

                  <?php       
                      require 'conn.php';
                      $query = mysqli_query($conn, "SELECT * FROM `tbl_tvlink`");
                      while($fetch = mysqli_fetch_array( $query)){
                  ?>

                    <li  class="d-flex align-items-center">
                        <?php  echo '<img src="data:image/jpeg;base64,'.base64_encode( $fetch['tv_image'] ).'" >';?>
                        <a href="<?php echo $fetch['tv_link']?>" target="_blank"><?php echo $fetch['tv_title']?> »</a>
                    </li>
                    <?php
                        }
                    ?>
                   
                  </ul>
                </div>
              </div>
        </div>
    </div>
</body>
</html>

Setup your database connection copy and paste the code below for your data source connection save and name it to conn.php .

<?php 
    $conn=mysqli_connect("localhost", "root", "", "db_tv");

        if(!$conn){
            die("Error: Failed To Connect Database!");
        }
?>

Let me know what you need just leave a message/comment  and I will do my very best to make that happen. I hope this simple codes will help you. Enjoy Coding!