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
AngularJS Visual Basic 6.0

CRUD AngularJS with modal boostrap using VB6 App

This tutorial we will make simple CRUD app Create a simple database table and fetch a database table using PHP and MySQL and returning to JSON, Update database table data and Delete data using AngularJS in vb6 application. I hope you have a basic understanding of AngularJS to implement it to your project. Add web browser component control into a Visual Basic 6 application. 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/ for AngularJS you can download it here https://angularjs.org/

Database Field Name

ADD REFERENCE TO YOUR PROJECT Check the selection box next to the component that you want to add. If the component is not listed, locate the .dll or .ocx file using Browse.

Create form to your project and double click the form to enter the code window Copy the code below and paste then save.

Private Sub Form_Activate()
    Me.WebBrowser1.Navigate2 "About:Blank"
    Call load
End Sub

Sub load()
setWindowSize
Me.WebBrowser1.Silent = True
With Me.WebBrowser1.Document
        .Write ("<!DOCTYPE html>")
        .Write ("<HTML lang='en' ng-app='Module_Product' >")
        .Write ("<head>")
        .Write ("<meta charset='utf-8'>")
        .Write ("<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>")
        .Write ("<link href=' " & App.Path & "\css\bootstrap.css" & " ' rel='stylesheet' type='text/css'>")
        .Write ("<link href=' " & App.Path & "\css\sweetalert.css" & " ' rel='stylesheet'>")
        
        .Write ("<style>")
        .Write ("html{ height: 100vh}")
        .Write ("body{")
        .Write ("background: rgb(235,233,249);/* Old browsers */")
        .Write ("background: -moz-linear-gradient(135deg, rgb(196, 192, 187) 0%, rgb(17, 6, 47) 50%, rgb(206, 199, 236) 51%, rgb(219, 200, 199) 100%);")
        .Write ("background: -webkit-linear-gradient(135deg, rgb(196, 192, 187) 0%, rgb(17, 6, 47) 50%, rgb(206, 199, 236) 51%, rgb(219, 200, 199) 100%);")
        .Write ("background: linear-gradient(135deg, rgb(196, 192, 187) 0%, rgb(17, 6, 47) 50%, rgb(206, 199, 236) 51%, rgb(219, 200, 199) 100%);")
        .Write ("filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ebe9f9', endColorstr='#c1bfea',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */")
        .Write ("color: #fff !important}")
        .Write (".modal-backdrop {opacity: 0.8}")
        .Write ("</style>")
        .Write ("</head>")
        .Write ("<script src=' " & App.Path & "\js\angular.min.js" & "'></script>")
        .Write ("<body>")
        .Write ("<div ng-app='myApp' ng-controller='myCtrl' id='my-app' class='mt-2 p-5 container'>")
        .Write ("<h4 class='mb-5'>CRUD AngularJS with modal boostrap using VB6 App</h4>")
        .Write ("<h1 class='mb-3' >My Product List Table</h1>")
        
        .Write ("<div class='modal' id='myModal' role='dialog'>")
        .Write ("<div id='modal-form' class='modal-dialog modal-lg'>")
        .Write ("<div class='modal-content'>")
        .Write ("<div class='modal-header'>")
         .Write ("<h4 class='text-success'>{{ formTitle }}</h4>")
        .Write ("<button type='button' class='close' data-dismiss='modal'>×</button>")
       
        .Write ("</div>")
        
        .Write ("<div class='modal-body'>")
        .Write ("<form  method='post'>")
        .Write ("<div class='form-group'>")
        .Write ("<label  class='text-primary'>NAME</label>")
        .Write ("<input type='text' class='form-control' id='name' name='name'  ng-model='name' placeholder='Enter product name'>")
        .Write ("</div>")
        
        .Write ("<div class='col-md-12 d-flex align-items-center p-0 m-0'>")
        .Write ("<div class='col-md-4 p-0'>")
        .Write ("<div class='form-group'>")
        .Write ("<label class='text-primary'>SKU</label>")
        .Write ("<input type='text' class='form-control' id='sku' ng-model='sku' placeholder='Enter stock unit'>")
        .Write ("</div>")
        .Write ("</div>")

        .Write ("<div class='col-md-4'>")
        .Write ("<div class='form-group'>")
        .Write ("<label class='text-primary'>PRICE</label>")
        .Write ("<input type='text' class='form-control' id='price' ng-model='price' placeholder='Enter price'>")
        .Write ("</div>")
        .Write ("</div>")

        .Write ("<div class='col-md-4  p-0'>")
        .Write ("<div class='form-group'>")
        .Write ("<label class='text-primary'>QUANTITY</label>")
        .Write ("<input type='text' class='form-control' id='qty' ng-model='qty'  placeholder='Enter quantity'>")
        .Write ("</div>")
        .Write ("</div>")
        .Write ("</div>")
        
        .Write ("<div class='form-group'>")
        .Write ("<label class='text-primary'>DESCRIPTION</label>")
        .Write ("<input type='text' class='form-control' id='description' ng-model='description'  placeholder='Enter description'>")
        .Write ("</div>")
        .Write (" <input id='btn-save' type='submit' class='btn btn-primary btn-add btn-block' ng-click='DisplayProduct()' value='{{btnName}}' />")
        .Write ("</form>")
        .Write ("</div>")
        
        .Write ("<input type='text' id='proid' ng-model='id' style='display:none'>")
        
        .Write ("<div class='modal-footer'>")
        .Write ("<button type='submit' class='btn btn-default btn-default pull-left' data-dismiss='modal'><span class='glyphicon glyphicon-remove'></span> Cancel</button>")
        .Write ("</div>")
        .Write ("</div>")
        .Write ("</div>")
        .Write ("</div>")
        
        .Write ("<div class='d-flex align-items-center mb-3' >")
        .Write ("<div>")
        .Write ("<a type='button' class='btn btn-info btn-lg' ng-click='addData()' href='#myModal' data-toggle='modal'>Add Product</a>")
        .Write ("</div>")
        
        .Write ("<div class='col-xs-6 ml-auto'>")
        .Write ("<input style='border: 1px solid black' class='ml-0 form-control ng-pristine ng-valid' ng-model='searchKeyword' type='text'>")
        .Write ("</div>")
        .Write ("</div>")
        
        .Write ("<label id='getbtn' style='display: none; color: black'class='info'></label>")
      
        .Write ("<table id='load-data' class='table table-striped table-hover' style='width:100%'>")
        .Write ("<thead>")
        .Write (" <tr>")
        .Write (" <th>#</th>")
        .Write (" <th>Name</th>")
        .Write (" <th>Sku</th>")
        .Write (" <th>Price</th>")
        .Write ("<th>Qty</th>")
        .Write ("<th>Description</th>")
        .Write ("<th>Availability</th>")
        .Write ("<th>Action</th>")
        .Write ("</tr>")
        .Write ("</thead>")
        .Write ("<tbody>")
        .Write ("<tr ng-repeat='product in products  | filter: searchKeyword' id='del1'>")
        .Write ("<td>{{$index+1}}</td>")
        .Write ("<td>{{ product.name }}</td>")
        .Write ("<td>{{ product.sku }}</td>")
        .Write ("<td>{{ product.price }}</td>")
        .Write ("<td>{{ product.qty }}</td>")
        .Write ("<td>{{ product.description }}</td>")
        .Write ("<td>{{ product.availability }}</td>")
        .Write ("<td class='data-action'>")
        .Write ("<a pro-edit='{{ product.id }}' href='#myModal' data-toggle='modal' ng-click='update_data(product.id, product.name, product.sku, product.price, product.qty, product.description)'  class='btn-color' style='border: 1px solid transparent;border-radius: 4px;padding: 5px 6px;background-color: #4766e8; margin-left: 5px;color: #fff;font-size: 12px; text-decoration: none' id='btn-edit' data-action='edit' href='javascript:void(0)'>EDIT</a>")
        .Write ("<a pro-del='{{ product.id }}' id='delete-data' class='btn-color' style='border: 1px solid transparent;border-radius: 4px;padding: 5px 6px;background-color: #ff0000; margin-left: 5px;color: #fff; font-size: 12px; text-decoration: none' data-id='del1' id='btn-delete' data-action='delete' href='javascript:void(0)' onclick='delete_data()'>DELETE</a>")
        .Write ("</td>")
        .Write ("</tr>")
       
        .Write ("</tbody>")
        .Write ("<tfoot>")
        .Write ("<tr>")
        .Write (" <th>#</th>")
        .Write (" <th>Name</th>")
        .Write (" <th>Sku</th>")
        .Write (" <th>Price</th>")
        .Write ("<th>Qty</th>")
        .Write ("<th>Description</th>")
        .Write ("<th>Availability</th>")
        .Write ("<th>Action</th>")
        .Write ("</tfoot>")
        .Write ("</table>")
        
        .Write ("<script src=' " & App.Path & "\js\jquery-3.3.1.js" & " '></script>")
        .Write ("<script src=' " & App.Path & "\js\bootstrap.min.js" & " '></script>")
        .Write ("<script src=' " & App.Path & "\js\sweetalert-dev.js" & " '></script>")
        .Write ("<script src=' " & App.Path & "\js\script.js" & " '></script>")
        
        .Write ("<script>")
        .Write ("$('#load-data tbody').on( 'click', '#delete-data', function () {")
        .Write ("var stuId = $(this).parents('tr');")
       
        .Write ("swal({title: 'Product will be deleted permanently!',")
        .Write ("text: 'You wont be able to revert this!',")
        .Write ("type: 'warning',")
        .Write ("allowOutsideClick: true,")
        .Write ("showCancelButton: true,")
        .Write ("confirmButtonColor: '#3085d6',")
        .Write ("cancelButtonColor: 'red',")
        .Write ("confirmButtonText: 'Yes, delete it!',")
        .Write ("cancelButtonText: 'No, cancel!',")
        .Write ("closeOnConfirm: false,")
        .Write ("closeOnCancel: true },")
        
        .Write ("function(isConfirm){")
        .Write ("if (isConfirm)")
        .Write ("{")
        .Write ("swal({")
        .Write ("title: 'success',")
        .Write ("text: 'Product has been deleted.',")
        .Write ("type: 'success',")
        .Write ("confirmButtonText: 'OK',")
        .Write ("allowOutsideClick: 'false'")
        .Write ("}, function () {")
        .Write ("stuId.remove();  document.getElementById('getbtn').innerHTML = 'DELETE';")
        .Write ("});")
        .Write ("}});")
    
        .Write ("} );")
        .Write ("</script>")
    
        .Write ("</div>")
        
        .Write ("<div id='footer' class='container bg-success text-center' style='border-radius: 3px; padding: 2px'>")
        .Write ("Copyright © 2020 https://proghubsterzeak.com/")
        .Write ("</div>")
        
        .Write ("</body>")
        
        .Write ("</html>")
        Me.WebBrowser1.Refresh2
        Me.WebBrowser1.Document.Script.Document.Clear
        Me.WebBrowser1.Document.Script.Document.Close
    End With
End Sub

Private Sub setWindowSize()
WebBrowser1.Height = Form1.Height
WebBrowser1.Width = Form1.Width
End Sub

Private Sub Form_Resize()
setWindowSize
End Sub

Private Sub txtbtn_Change()
On Error Resume Next
If Me.txtbtn.Text = "SAVE" Then
Create_Recordset rstProduct, "Select * from tbl_products where name like'" & Me.txtname.Text & "'", myConn
If rstProduct.RecordCount = 1 Then
Exit Sub
End If
myConn.Execute "INSERT INTO tbl_products (name,sku,price,qty,description) value ('" & Me.txtname.Text & "','" & Me.txtsku.Text & "','" & Me.txtprice.Text & "','" & Me.txtqty.Text & "','" & Me.txtdes.Text & "')"
ElseIf Me.txtbtn.Text = "UPDATE" Then
myConn.Execute "UPDATE tbl_products SET name = '" & Me.txtname.Text & "', sku = '" & Me.txtsku.Text & "', price = '" & Me.txtprice.Text & "', qty = '" & Me.txtqty.Text & "', description = '" & Me.txtdes.Text & "' Where id = '" & Me.txtid.Text & "'"
ElseIf Me.txtbtn.Text = "DELETE" Then
On Error Resume Next
myConn.Execute "DELETE from tbl_products where id = " & Me.txtaction.Text
End If
Me.txtid.Text = ""
Me.txtname.Text = ""
Me.txtsku.Text = ""
Me.txtprice.Text = ""
Me.txtqty.Text = ""
Me.txtdes.Text = ""
Me.txtbtn.Text = ""
Me.txtaction.Text = ""
rstProduct.Requery
End Sub

Private Sub WebBrowser1_CommandStateChange(ByVal Command As Long, ByVal Enable As Boolean)
  On Error Resume Next
        Set HTMLdoc = WebBrowser1.Document
        Me.txtbtn.Text = WebBrowser1.Document.getElementById("getbtn").innerHTML
        Me.txtaction.Text = HTMLdoc.activeElement.getAttribute("pro-del")
        Me.txtaction.Text = HTMLdoc.activeElement.getAttribute("pro-edit")
        Me.txtname.Text = WebBrowser1.Document.getElementById("name").Value
        Me.txtsku.Text = WebBrowser1.Document.getElementById("sku").Value
        Me.txtprice.Text = WebBrowser1.Document.getElementById("price").Value
        Me.txtqty.Text = WebBrowser1.Document.getElementById("qty").Value
        Me.txtdes.Text = WebBrowser1.Document.getElementById("description").Value
        Me.txtid.Text = WebBrowser1.Document.getElementById("proid").Value
End Sub

Setup your mysql database connection Create a folder inside local server and rename the folder as “angular_crud” copy and paste the code below and save it as product.php to the folder created. This code will fetch data from database and return to JSON. Make sure you’ve run Apache and MySQL as services. In order to run the program you must do these steps correctly.

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

	include 'conn.php';
	$product = array();

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

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

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!

Categories
AngularJS Visual Basic 6.0

Display Data with PHP & AngularJS in VB6

This tutorial we will display data using PHP and MySQL and returning it to JSON using AngularJS in vb6 application. I hope you have a basic understanding of AngularJS to implement it to your project. Add web browser component control into a Visual Basic 6 application. 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/ for AngularJS you can download it here https://angularjs.org/

Database Field Name

ADD REFERENCE TO YOUR PROJECT Check the selection box next to the component that you want to add. If the component is not listed, locate the .dll or .ocx file using Browse.

Create form to your project and double click the form to enter the code window Copy the code below and paste then save it.

Private Sub Form_Activate()
    Me.WebBrowser1.Navigate2 "About:Blank"
    Call load
End Sub

Sub load()
setWindowSize
Me.WebBrowser1.Silent = True
With Me.WebBrowser1.Document
    .Write ("<!DOCTYPE html>")
    .Write ("<html lang='en'>")
    
    .Write ("<head>")
    .Write ("<meta charset='UTF-8'>")
    .Write ("<meta name='viewport' content='width=device-width, initial-scale=1.0'>")
    .Write ("<meta http-equiv='X-UA-Compatible' content='ie=edge'>")
    .Write ("<title>Document</title>")
    .Write ("<link href=' " & App.Path & "\css\bootstrap.css" & " ' rel='stylesheet' type='text/css'>")
    .Write ("</head>")
    .Write ("<script src=' " & App.Path & "\js\angular.min.js" & "'></script>")
    
    .Write ("<body>")
    
    .Write ("<div ng-app='myApp' ng-controller='myCtrl'>")
    .Write ("<div class='container'>")
    .Write ("<h1 class='pl-5 pt-5'>DASHBOARD</h1>")
    .Write ("<p class='pl-5'>My First AngularJS in VB6</p>")
    .Write ("<div class='p-5 card-deck mb-3 text-center' >")
    
    .Write ("<div  ng-repeat='bill in bills' class='card mb-4 box-shadow'>")
    .Write ("<div class='card-header'>")
    .Write ("<h4 class='my-0 font-weight-normal' >{{ bill.fullname }}</h4>")
    .Write ("</div>")
    .Write ("<div class='card-body {{ bill.status }}'>")
    .Write ("<h1 class='card-title'>${{ bill.mondue }} <small class='text-muted'>/ mo</small>")
    .Write ("<h1>")
    .Write ("</div>")
    .Write ("</div>")

    .Write ("</div>")
    
    .Write ("<div id='footer' class=' text-center'>")
    .Write ("Copyright © 2020 http://proghubsterzeak.com/")
    .Write ("</div>")
    
    .Write ("</div>")
    .Write ("</div>")
    
    .Write ("<script>")
    .Write ("var app = angular.module('myApp', []);")
    .Write ("app.controller('myCtrl', function($scope, $http) {")
    .Write ("$http.get('http://localhost/angularjs/fetch.php')")
    .Write (".then(function (response) {$scope.bills = response.data.records;});")
    .Write ("});")
    .Write ("</script>")
    
    .Write ("</body>")
    
    .Write ("</html>")
    Me.WebBrowser1.Refresh2
End With
End Sub

Private Sub setWindowSize()
WebBrowser1.Height = Form1.Height
WebBrowser1.Width = Form1.Width
End Sub

Private Sub Form_Resize()
setWindowSize
End Sub

Setup your mysql database connection Create a folder inside C:\xampp\htdocs\ rename the folder as “angularjs” copy and paste the code below and save it as fetch.php to the folder created. This code will fetch data from database and return it to JSON. Make sure you’ve run Apache and MySQL as services. In order to run the program you must do these steps correctly.

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("localhost", "root", "", "db_bill");

$result = $conn->query("SELECT fullname, mon_due, status FROM tbl_client");

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "") {$outp .= ",";}
    $outp .= '{"fullname":"'  . $rs["fullname"] . '",';
    $outp .= '"status":"'  . $rs["status"] . '",';
    $outp .= '"mondue":"'. $rs["mon_due"]     . '"}'; 
}
$outp ='{"records":['.$outp.']}';
$conn->close();

echo($outp);
?>

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!

Categories
AngularJS Visual Basic 6.0

Login with AngularJS in VB6 Application

We will Integrate AngularJS Login in vb6 application with MySQL Database. I hope you have a basic understanding of AngularJS to implement it to your project. Add web browser component control into a Visual Basic 6 application. 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/ for AngularJS you can download it here https://angularjs.org/

Database Field Name

ADD REFERENCE TO YOUR PROJECT Check the selection box next to the component that you want to add. If the component is not listed, locate the .dll or .ocx file using Browse.

Create form to your project and double click the form to enter the code window Copy the code below and paste then save it.

Private Sub Form_Activate()
    Me.WebBrowser1.Navigate2 "About:Blank"
    Call load
End Sub

Sub load()
setWindowSize
Me.WebBrowser1.Silent = True
With Me.WebBrowser1.Document
    .Write ("<!DOCTYPE html>")
    .Write ("<html lang='en'>")
    
    .Write ("<head>")
    .Write ("<meta charset='UTF-8'>")
    .Write ("<meta name='viewport' content='width=device-width, initial-scale=1.0'>")
    .Write ("<meta http-equiv='X-UA-Compatible' content='ie=edge'>")
    .Write ("<title>Document</title>")
    .Write ("<link href=' " & App.Path & "\css\bootstrap.css" & " ' rel='stylesheet' type='text/css'>")
    .Write ("<style>")
    .Write ("html {height: 100%;}")
    
    .Write ("body {background: #445e93;}")
    
    .Write (".login-wrapper {width: 360px;margin: 7% auto;background: #fff;padding: 20px; border-top: 0;color: #666;}")
    
    .Write (".form-control {border-radius: 0;box-shadow: none;border-color: #d2d6de;}")
    
    .Write (".form-control:focus {border-color: #3c8dbc;box-shadow: none;}")
    
    .Write (".form-control::placeholder {color: #999;opacity: 1;font-size: 14px;}")
    
    .Write (".btn.btn-flat {border-radius: 0;-webkit-box-shadow: none;-moz-box-shadow: none;box-shadow: none;")
    .Write ("border-width: 1px;}")

    .Write (".btn-primary {background-color: #3c8dbc;border-color: #367fa9;}")
    
    .Write (".form-group { position: relative;}")
    
    .Write ("img {width: 100%; max-width: 15px;}")
    
    .Write ("span { position: absolute;right: 12px;top: 9%;}")
    .Write ("</style>")
    .Write ("</head>")
    .Write ("<script src=' " & App.Path & "\js\angular.min.js" & "'></script>")
    
    .Write ("<body>")
    
    .Write ("<div ng-app='myApp' ng-controller='myCtrl'>")
    .Write ("<div class='container'>")
    .Write ("<h1 class='pt-5 text-center text-warning'>WELCOME USER</h1>")
    .Write ("<p class='text-center text-white'>Login using AngularJS  in VB6</p>")
    
    .Write ("<div class='login-wrapper'>")
    .Write ("<div class='login-title text-center pb-3'>")
    .Write ("<h3>Login Security System</h3>")
    .Write ("</div>")
    .Write ("<div ng-show='showlogin' class='login-body'>")
    .Write ("<div class='form-group '>")
    .Write ("<input type='email' ng-model='email' class='form-control' name='email' id='email' placeholder='Email' autocomplete='off'>")
    .Write ("<span><img src=' " & App.Path & "\images\user.png" & "'></span>")
    .Write ("</div>")
    .Write ("<div class='form-group'>")
    .Write ("<input type='password' ng-model='password' class='form-control' name='password' id='password' placeholder='Password' autocomplete='off'>")
    .Write ("<span><img src=' " & App.Path & "\images\locked.png" & "'></span>")
    .Write ("</div>")
    .Write ("</div>")
    .Write ("<div class='d-flex align-items-center'>")
    .Write ("<div class='col-md-8 p-0 d-flex align-items-center'>")
    .Write ("<input ng-show='showcheck' type='checkbox' name='' id=''> <p style='margin-top: 13px; margin-left: 5px' ng-show='showtext' >Remember Me</p>")
    .Write ("</div>")
    
    .Write ("<div class='col-md-4 p-0'>")
    .Write ("<button type='submit' ng-show='showsignin' ng-click='login()' class='btn btn-primary btn-block btn-flat'>Sign In</button>")
     .Write ("<button type='submit' ng-show='showlogout' ng-click='logout()' class='btn btn-primary btn-block btn-flat'>Sign Out</button>")
    .Write ("</div>")
    
    .Write ("</div>")
    .Write ("</div>")

    .Write ("<div id='footer' class='text-white text-center'>")
    .Write ("Copyright © 2020 http://proghubsterzeak.com/")
    .Write ("</div>")
    
    .Write ("</div>")
    .Write ("</div>")
    
    Create_Recordset rstUser, "Select * from tbl_users ", myConn
    .Write ("<script>")
    .Write ("var app = angular.module('myApp', []);")
    .Write ("app.controller('myCtrl', function($scope) {")
    .Write ("$scope.username = '" & rstUser![email] & "';")
    .Write ("$scope.pass = '" & rstUser![password] & "';")
    .Write ("$scope.showlogin = true;")
    .Write ("$scope.showlogout = false;")
    .Write ("$scope.showsignin = true;")
    .Write ("$scope.showcheck = true;")
    .Write ("$scope.showtext = true;")
    
    .Write ("$scope.login = function() {")
    .Write ("if ($scope.email == null || $scope.password == null) {")
    .Write ("alert('Please complete the required fields');")
    .Write ("} else {")
    
    .Write ("if ($scope.username != $scope.email || $scope.password != $scope.pass) {")
    .Write ("alert('Invalid Email and Password');")
    .Write ("} else {")
    .Write ("alert('Login Successfully!');")
    .Write ("$scope.showlogin = false;")
    .Write ("$scope.showlogout = true;")
    .Write ("$scope.showcheck = false;")
    .Write ("$scope.showsignin = false;")
    .Write ("$scope.showtext = false;")
    .Write ("};")
    
    .Write ("}")
    .Write ("}")
    
    .Write ("});")
    .Write ("</script>")

    .Write ("</body>")
    
    .Write ("</html>")
    Me.WebBrowser1.Refresh2
End With
End Sub

Private Sub setWindowSize()
WebBrowser1.Height = Form1.Height
WebBrowser1.Width = Form1.Width
End Sub

Private Sub Form_Resize()
setWindowSize
End Sub

Setup your database connection create Modules to your project copy and paste the code below for your data source connection.

Public myConn As ADODB.Connection
Public rstUser As ADODB.Recordset

Sub main()
MySqlConn myConn, "db_user"
Form1.Show
End Sub

Public Sub MySqlConn(SQLConn As Connection, CDatabase As String)
    Set SQLConn = New ADODB.Connection
    SQLConn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver};SERVER=127.0.0.1;Database=" & CDatabase & ";UID=root;Option=3;"
    SQLConn.Open
    SQLConn.CursorLocation = adUseClient
End Sub

Public Sub Create_Recordset(rst As Recordset, SQL As String, CConnection As Connection)
        Set rst = New ADODB.Recordset
        rst.Open SQL, CConnection, adOpenDynamic, adLockBatchOptimistic
End Sub

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!