article

Wednesday, January 5, 2022

PHP Mysqli OOP Date Range Filter Ajax DataTables

PHP Mysqli OOP Date Range Filter Ajax DataTables

Bootstrap CDN
https://getbootstrap.com/docs/4.3/getting-started/introduction/

https://jqueryui.com/datepicker/
The datepicker is tied to a standard form input field. Focus on the input (click, or use the tab key) to open an interactive calendar in a small overlay. Choose a date, click elsewhere on the page (blur the input), or hit the Esc key to close.

https://datatables.net/

DataTables is a powerful jQuery plugin for creating table listings and adding interactions to them. It provides searching, sorting and pagination without any configuration.

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL,
  `created_at` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`, `created_at`) VALUES
(1, 'Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '2020-01-09'),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '2020-02-15'),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '2020-03-01'),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '2020-01-24'),
(5, 'Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '2020-01-11'),
(6, 'Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '2020-02-23'),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456, '2020-03-04'),
(9, 'Airi Satou updated', 'Pre-Sales Support updated', 'New York', 25, 4568, '2020-04-28'),
(10, 'Angelica Ramos updated', 'Sales Assistant updated', 'New York', 45, 456, '2020-01-12'),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '2020-02-06'),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '2020-03-21'),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '2020-04-14'),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '2020-01-29'),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465, '2020-02-22'),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '2020-03-10'),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '2020-04-26'),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '2020-01-17'),
(19, 'Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '2020-02-01'),
(20, 'Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '2020-03-19'),
(21, 'Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '2020-04-21');

ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
index.php
//index.php
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

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

	<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
	<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
	
	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

    <!-- Datatables -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css" />
	<script type="text/javascript"src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
	
    <title>PHP Mysqli OOP Date Range Filter Ajax Datatables</title>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-12 mt-5">
                <h1 class="text-center">PHP Mysqli OOP Date Range Filter Ajax DataTables</h1>
                <hr>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-6">
                        <div class="input-group mb-3">
                            <div class="input-group-prepend">
                                <span class="input-group-text bg-info text-white" id="basic-addon1"><i class="fas fa-calendar-alt"></i></span>
                            </div>
                            <input type="text" class="form-control" id="start_date" placeholder="Start Date">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="input-group mb-3">
                            <div class="input-group-prepend">
                                <span class="input-group-text bg-info text-white" id="basic-addon1"><i class="fas fa-calendar-alt"></i></span>
                            </div>
                            <input type="text" class="form-control" id="end_date" placeholder="End Date">
                        </div>
                    </div>
                </div>
                <div>
                    <button id="filter" class="btn btn-outline-info btn-sm">Filter</button>
                    <button id="reset" class="btn btn-outline-warning btn-sm">Reset</button>
                </div>
                <div class="row mt-3">
                    <div class="col-md-12">
                        <div class="table-responsive">
                            <table class="table table-borderless display nowrap" id="records" style="width:100%">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Position</th>
                                        <th>Office</th>
                                        <th>Salary</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Font Awesome -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script>
    <script>
    $(function() {
        $("#start_date").datepicker({
            "dateFormat": "yy-mm-dd"
        });
        $("#end_date").datepicker({
            "dateFormat": "yy-mm-dd"
        });
    });
    // Fetch records
    function fetch(start_date, end_date) {
        $.ajax({
            url: "records.php",
            type: "POST",
            data: {
                start_date: start_date,
                end_date: end_date
            },
            dataType: "json",
            success: function(data) {
                // Datatables
                var i = "1";

                $('#records').DataTable({
                    "data": data,
                    "dom": "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-4'B><'col-sm-12 col-md-4'f>>" +
                        "<'row'<'col-sm-12'tr>>" +
                        "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
                    // responsive
                    "responsive": true,
                    "columns": [{
                            "data": "id"
                        },
                        {
                            "data": "name"
                        },
                        {
                            "data": "position"
                        },
                        {
                            "data": "office"
                        },
                        {
                            "data": "salary"
                        },
                        {
                            "data": "created_at"
                        }
                    ]
                });
            }
        });
    }
    fetch();

    // Filter
    $(document).on("click", "#filter", function(e) {
        e.preventDefault();

        var start_date = $("#start_date").val();
        var end_date = $("#end_date").val();

        if (start_date == "" || end_date == "") {
            alert("both date required");
        } else {
            $('#records').DataTable().destroy();
            fetch(start_date, end_date);
        }
    });

    // Reset
    $(document).on("click", "#reset", function(e) {
        e.preventDefault();

        $("#start_date").val(''); // empty value
        $("#end_date").val('');

        $('#records').DataTable().destroy();
        fetch();
    });
    </script>
</body>
</html>
records.php
//records.php
<?php
include 'model.php';

$model = new Model();

if (isset($_POST['start_date']) && isset($_POST['end_date'])) {
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];

    $rows = $model->date_range($start_date, $end_date);
} else {
    $rows = $model->fetch();
}
echo json_encode($rows);
model.php
//model.php
<?php
class Model
{
    private $server = "localhost";
    private $username = "root";
    private $password = "";
    private $db = "testingdb";
    private $conn;

    public function __construct()
    {
        try {
            $this->conn = new mysqli($this->server, $this->username, $this->password, $this->db);
        } catch (\Throwable $th) {
            //throw $th;
            echo "Connection error " . $th->getMessage();
        }
    }

    public function fetch()
    {
        $data = [];

        $query = "SELECT * FROM employee";
        if ($sql = $this->conn->query($query)) {
            while ($row = mysqli_fetch_assoc($sql)) {
                $data[] = $row;
            }
        }

        return $data;
    }

    public function date_range($start_date, $end_date)
    {
        $data = [];

        if (isset($start_date) && isset($end_date)) {
            $query = "SELECT * FROM employee WHERE created_at > '$start_date' AND created_at < '$end_date'";
            if ($sql = $this->conn->query($query)) {
                while ($row = mysqli_fetch_assoc($sql)) {
                    $data[] = $row;
                }
            }
        }

        return $data;
    }
}

Tuesday, January 4, 2022

SwiftUI Share Sheet

SwiftUI Share Sheet

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev15ios
//
//  Created by Cairocoders on 11/8/21.
//

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        VStack(spacing: 15){
            
            HStack(spacing: 15){
                
                Button(action: {

                }) {
                    Image(systemName: "arrow.left").foregroundColor(Color.white)
                }
                
                Spacer()
                
                Button(action: {
                    share()
                }) {
                    Image("share").renderingMode(.original)
                }
                
                Button(action: {
                    
                }) {
                    Image(systemName: "info.circle").foregroundColor(Color.white)
                }
                
            }.padding()
            
            ZStack{
                Image("detail").resizable()
            }.frame(height: UIScreen.main.bounds.height / 2)
            .navigationBarTitle("")
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
            
            ScrollView(.vertical, showsIndicators: false) {
                VStack(alignment: .leading, spacing: 15){
                    HStack{
                        Text("Details")
                    }
                }
                
            }.padding(.top, 15)
            .padding(.horizontal, 15)
            Spacer()
            
        }.preferredColorScheme(.dark)
    }
    
    func share() {
        guard let urlShare = URL(string: "https://developer.apple.com/xcode/swiftui/") else { return }
        let activityVC = UIActivityViewController(activityItems: [urlShare], applicationActivities: nil)
           UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Sunday, January 2, 2022

Vuejs PHP Mysqli OOP CRUD (Create, Read, Update and Delete)

Vuejs PHP Mysqli OOP CRUD (Create, Read, Update and Delete)

Download or Include 

https://bootstrap-vue.org/

https://bootstrap-vue.org/docs/components/modal#modals

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

CREATE TABLE `member` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `member`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `member`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

//index.php
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
    <link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />

    <title>Vuejs PHP Mysqli OOP CRUD (Create, Read, Update and Delete)</title>

    <style>
      [v-cloak] {
        display: none;
      }
    </style>

  </head>
  <body>
    <div class="container" id="vuejscrudapp" v-cloak>
      <div class="row">
        <div class="col-md-12 mt-5">
          <h1 class="text-center">Vuejs PHP Mysqli OOP CRUD (Create, Read, Update and Delete)</h1>
          <hr>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12">

          <!-- Add Records -->
          <div>
            <b-button id="show-btn" @click="showModal('my-modal')">Add Records</b-button>

            <b-modal ref="my-modal" hide-footer title="Add Records">
              <div>
                <form action="" @submit.prevent="onSubmit">
                  <div class="form-group">
                    <label for="">Name</label>
                    <input type="text" v-model="name" class="form-control">
                  </div>
                  <div class="form-group">
                    <label for="">Email</label>
                    <input type="email" v-model="email" class="form-control">
                  </div>
                  <div class="form-group">
                    <button class="btn btn-sm btn-outline-info">Add Records</button>
                  </div>
                </form>
              </div>
              <b-button class="mt-3" variant="outline-danger" block @click="hideModal('my-modal')">Close Me</b-button>
            </b-modal>
          </div>

          <!-- Update Record -->
          <div>
            <b-modal ref="my-modal1" hide-footer title="Update Record">
              <div>
                <form action="" @submit.prevent="onUpdate">
                  <div class="form-group">
                    <label for="">Name</label>
                    <input type="text" v-model="edit_name" class="form-control">
                  </div>
                  <div class="form-group">
                    <label for="">Email</label>
                    <input type="email" v-model="edit_email" class="form-control">
                  </div>
                  <div class="form-group">
                    <button class="btn btn-sm btn-outline-info">Update Record</button>
                  </div>
                </form>
              </div>
              <b-button class="mt-3" variant="outline-danger" block @click="hideModal('my-modal1')">Close Me</b-button>
            </b-modal>
          </div>
        </div>
      </div>
      <div class="row" v-if="records.length">
        <div class="col-md-12">
          <table class="table table-striped table-bordered">
            <thead>
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(record, i) in records" :key="record.id">
                <td>{{i + 1}}</td>
                <td>{{record.name}}</td>
                <td>{{record.email}}</td>
                <td>
                  <button @click="deleteRecord(record.id)" class="btn btn-sm btn-outline-danger">Delete</button>
                  <button @click="editRecord(record.id)" class="btn btn-sm btn-outline-info">Edit</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <!-- BootstrapVue js -->
    <script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
    <!-- Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<script>
      var app = new Vue({
        el: '#vuejscrudapp',
        data: {
          name: '',
          email: '',
          records: [],
          edit_id: '',
          edit_name: '',
          edit_email: ''
        },

        methods: {
          showModal(id) {
            this.$refs[id].show()
          },
          hideModal(id) {
            this.$refs[id].hide()
          },

          onSubmit(){
            if (this.name !== '' && this.email !== '') {
              var fd = new FormData()

              fd.append('name', this.name)
              fd.append('email', this.email)

              axios({
                url: 'insert.php',
                method: 'post',
                data: fd
              })
              .then(res => {
                // console.log(res)
                if (res.data.res == 'success') {
                  alert('record added')
                  this.name = ''
                  this.email = ''

                  app.hideModal('my-modal')
                  app.getRecords()
                }else{
                  alert('error')
                }
              })
              .catch(err => {
                console.log(err)
              })
            }else{
              alert('empty')
            }
          },

          getRecords(){
            axios({
              url: 'records.php',
              method: 'get'
            })
            .then(res => {
              // console.log(res)
              this.records = res.data.rows
            })
            .catch(err => {
              console.log(err)
            })
          },

          deleteRecord(id){
            if (window.confirm('Delete this record')) {
              var fd = new FormData()

              fd.append('id', id)

              axios({
                url: 'delete.php',
                method: 'post',
                data: fd
              })
              .then(res => {
                // console.log(res)
                if (res.data.res == 'success') {
                  alert('delete successfully')
                  app.getRecords();
                }else{
                  alert('error')
                }
              })
              .catch(err => {
                console.log(err)
              })
            }
          },

          editRecord(id){
            var fd = new FormData()

            fd.append('id', id)

            axios({
              url: 'edit.php',
              method: 'post',
              data: fd
            })
            .then(res => {
              if (res.data.res == 'success') {
                this.edit_id = res.data.row[0]
                this.edit_name = res.data.row[1]
                this.edit_email = res.data.row[2]
                app.showModal('my-modal1')
              }
            })
            .catch(err => {
              console.log(err)
            })
          },

          onUpdate(){
            if (this.edit_name !== '' && this.edit_email !== '' && this.edit_id !== '') {

              var fd = new FormData()

              fd.append('id', this.edit_id)
              fd.append('name', this.edit_name)
              fd.append('email', this.edit_email)

              axios({
                url: 'update.php',
                method: 'post',
                data: fd
              })
              .then(res => {
                // console.log(res)
                if (res.data.res == 'success') {
                  alert('record update');

                  this.edit_name = '';
                  this.edit_email = '';
                  this.edit_id = '';

                  app.hideModal('my-modal1');
                  app.getRecords();
                }
              })
              .catch(err => {
                console.log(err)
              })

            }else{
              alert('empty')
            }
          }

        },

        mounted: function(){
          this.getRecords()
        }
      })
</script>
</body>	
</html>
Model.php
//Model.php
<?php 

	Class Model{
		private $server = 'localhost';
		private $username = 'root';
		private $password = '';
		private $db = 'testingdb';
		private $conn;

		public function __construct(){
			try {
				$this->conn = new mysqli($this->server, $this->username, $this->password, $this->db);
			} catch (Exception $e) {
				echo "Connection error " . $e->getMessage();
			}
		}

		public function insert($name, $email){
			$query = "INSERT INTO member (`name`, `email`) VALUES ('$name', '$email')";
			if ($sql = $this->conn->query($query)) {
				return true;
			}else{
				return;
			}
		}

		public function fetch(){
			$data = [];

			$query = "SELECT * FROM member";

			if ($sql = $this->conn->query($query)) {
				while ($rows = mysqli_fetch_assoc($sql)) {
					$data[] = $rows;
				}
			}

			return $data;
		}

		public function delete($id){
			$query = "DELETE FROM member WHERE `id` = '$id'";
			if ($sql = $this->conn->query($query)) {
				return true;
			}else{
				return;
			}
		}

		public function edit($id){
			$data = [];

			$query = "SELECT * FROM member WHERE `id` = '$id'";
			if ($sql = $this->conn->query($query)) {
				$row = mysqli_fetch_row($sql);
				$data = $row;
			}

			return $data;
		}

		public function update($id, $name, $email){
			$query = "UPDATE member SET `name` = '$name', `email` = '$email' WHERE `id` = '$id'";
			if ($sql = $this->conn->query($query)) {
				return true;
			}else{
				return;
			}
		}
	}

 ?>
 
insert.php
//insert.php
<?php 
	if (isset($_POST['name']) && isset($_POST['email'])) {
		$name = $_POST['name'];
		$email = $_POST['email'];

		include 'model.php';

		$model = new Model();

		if ($model->insert($name, $email)) {
			$data = array('res' => 'success');
		}else{
			$data = array('res' => 'error');
		}

		echo json_encode($data);
	}
 ?>
 
edit.php
//edit.php
<?php 
	if (isset($_POST['id'])) {
		$id = $_POST['id'];

		include 'model.php';

		$model = new Model();

		if ($row = $model->edit($id)) {
			$data = array('res' => 'success', 'row' => $row);
		}else{
			$data = array('res' => 'error');
		}

		echo json_encode($data);
	}
 ?>
 
update.php
//update.php
<?php 
	if (isset($_POST['id']) && isset($_POST['name']) && isset($_POST['email'])) {
		
		$id = $_POST['id'];
		$name = $_POST['name'];
		$email = $_POST['email'];

		include 'model.php';

		$model = new Model();

		if ($model->update($id, $name, $email)) {
			$data = array('res' => 'success');
		}else{
			$data = array('res' => 'error');
		}

		echo json_encode($data);
	}
 ?>
 
delete.php
//delete.php
<?php 
	if (isset($_POST['id'])) {
		$id = $_POST['id'];

		include 'model.php';

		$model = new Model();

		if ($model->delete($id)) {
			$data = array('res' => 'success');
		}else{
			$data = array('res' => 'error');
		}

		echo json_encode($data);
	}
 ?>
 
records.php
//records.php
<?php 
	include 'model.php';

	$model = new Model();

	$rows = $model->fetch();

	$data = array('rows' => $rows);

	echo json_encode($data);
 ?>
 

Saturday, December 25, 2021

PHP Mysqli Limit Login Attempt Validation

PHP Mysqli Limit Login Attempt Validation

How to create a login attemp validation after 3 or more unsuccessful login a user is temporarily block

CREATE TABLE `tbluser` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `username` varchar(150) NOT NULL,
  `password` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `tbluser` (`id`, `name`, `username`, `password`) VALUES
(1, 'Cairocoders Ednalan', 'cairocoders', '$2y$10$dVB/4QU4vkrXB1.TAemkUuBELMHP73xFLVhP.SvPYV9l1dvmrDO4O'),
(2, 'tutorial101', 'clded25', '123456'),
(3, 'Clydey Ednalan', 'clyde0130', '123456');

ALTER TABLE `tbluser`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `tbluser`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
index.php
//index.php
<?php
	session_start();
	//check if can login again
	if(isset($_SESSION['attempt_again'])){
		$now = time();
		if($now >= $_SESSION['attempt_again']){
			unset($_SESSION['attempt']);
			unset($_SESSION['attempt_again']);
		}
	}
 //echo password_hash("123456", PASSWORD_DEFAULT);
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"> 
	<title>PHP Mysqli Login Attempt Validation</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
</head>
<body>
    <div id="login">
        <h3 class="text-center text-white pt-5">PHP Mysqli Login Attempt Validation</h3>
        <div class="container">
            <div id="login-row" class="row justify-content-center align-items-center">
                <div id="login-column" class="col-md-6">
                    <div id="login-box" class="col-md-12">
						<form id="login-form" class="form" method="POST" action="login.php">
                            <h3 class="text-center text-info">Login</h3>
                            <div class="form-group">
                                <label for="username" class="text-info">Username:</label><br>
								<input type="text" name="username" id="username" class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="password" class="text-info">Password:</label><br>
								<input type="password" name="password" id="password" class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="remember-me" class="text-info"><span>Remember me</span> <span><input id="remember-me" name="remember-me" type="checkbox"></span></label><br>
								<button type="submit" name="login" class="btn btn-info btn-md"> Login</button>
                            </div>
                            <div id="register-link" class="text-right">
                                <a href="#" class="text-info">Register here</a>
                            </div>
                        </form>
			<?php
				if(isset($_SESSION['error'])){
					?>
					<div class="alert alert-danger text-center" style="margin-top:40px;">
						<?php echo $_SESSION['error']; ?>
					</div>
					<?php
 
					unset($_SESSION['error']);
				}
 
				if(isset($_SESSION['success'])){
					?>
					<div class="alert alert-success text-center" style="margin-top:40px;">
						<?php echo $_SESSION['success']; ?>
					</div>
					<?php
 
					unset($_SESSION['success']);
				}
			?>
                    </div>
                </div>
            </div>
        </div>
<style>
body {
  margin: 0;
  padding: 0;
  background-color: #17a2b8;
}
#login .container #login-row #login-column #login-box {
  margin-top: 60px;
  max-width: 600px;
  height: 400px;
  border: 1px solid #9C9C9C;
  background-color: #EAEAEA;
}
#login .container #login-row #login-column #login-box #login-form {
  padding: 20px;
}
#login .container #login-row #login-column #login-box #login-form #register-link {
  margin-top: -85px;
}
</style>
</body>
</html>
login.php
//login.php
<?php
	session_start();
 
	if(isset($_POST['login'])){
		$conn = new mysqli('localhost', 'root', '', 'testingdb');
 
		//set login attempt if not set
		if(!isset($_SESSION['attempt'])){
			$_SESSION['attempt'] = 0;
		}
 
		//check if there are 3 attempts already
		if($_SESSION['attempt'] == 3){
			$_SESSION['error'] = 'Attempt limit reach';
		}else{
			$sql = "SELECT * FROM tbluser WHERE username = '".$_POST['username']."'";
			$query = $conn->query($sql); 
			if($query->num_rows > 0){
				$row = $query->fetch_assoc();
				//verify password
				if(password_verify($_POST['password'], $row['password'])){
					//action after a successful login
					//for now just message a successful login
					$_SESSION['success'] = 'Login successful';
					//unset our attempt
					unset($_SESSION['attempt']);
				}else{
					$_SESSION['error'] = 'Password incorrect';
					//this is where we put our 3 attempt limit
					$_SESSION['attempt'] += 1;
					//set the time to allow login if third attempt is reach
					if($_SESSION['attempt'] == 3){
						$_SESSION['attempt_again'] = time() + (5*60);
						//note 5*60 = 5mins, 60*60 = 1hr, to set to 2hrs change it to 2*60*60
					}
				}
			}else{
				$_SESSION['error'] = 'No account with that username';
			}
 
		}
 
	}
	else{
		$_SESSION['error'] = 'Fill up login form first';
	}
 
	header('location: index.php');
 
?>

Friday, December 24, 2021

Angular JS PHP Mysql Login

Angular JS PHP Mysql Login

angularjs CDN https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

CREATE TABLE `tbluser` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `username` varchar(150) NOT NULL,
  `password` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `tbluser` (`id`, `name`, `username`, `password`) VALUES
(1, 'Cairocoders Ednalan', 'cairocoders', '123456'),
(2, 'tutorial101', 'clded25', '123456'),
(3, 'Clydey Ednalan', 'clyde0130', '123456');

ALTER TABLE `tbluser`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `tbluser`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
index.php
//index.php
<?php
	session_start();
	if(isset($_SESSION['user'])){
		header('location:home.php');
	}
?>
<!DOCTYPE html>
<html ng-app="myapp" ng-controller="controller">
<head>
<title>Angular JS PHP Mysql Login</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> 
</head>
<body>
<div class="container">
	<center><h2 style="color:#fff;">Angular JS PHP Mysql Login</h2></center>
    <div class="card card-login mx-auto text-center bg-dark">
        <div class="card-header mx-auto bg-dark">
            <span> <img src="myglogo.png" width="100" alt="Logo"/> </span><br/>
            <span class="logo_title mt-5"> Login Account </span>
        </div>
        <div class="card-body">
            <form ng-submit="myFunct()">
                <div class="input-group form-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text"><i class="fas fa-user"></i></span>
                    </div>
                    <input type="text" class="form-control" placeholder="Username" name="username" id="username" ng-model="username" autofocus>
                </div>

                <div class="input-group form-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text"><i class="fas fa-key"></i></span>
                    </div>
                    <input type="password" class="form-control" placeholder="Password" name="password" id="password" ng-model="password">
                </div>

                <div class="form-group">
					<button type="submit" class="btn btn-outline-danger float-right login_btn" ng-click="login()"><span class="glyphicon glyphicon-log-in"></span> {{btnName}}</button>
                </div>
            </form>
        </div>
		<div ng-if="message">
		<div class="alert alert-success"><center>{{message}}</center></div>
		</div>
    </div>
</div>
<script>
var app = angular.module("myapp", []);
app.controller("controller", function($scope, $http) {
	$scope.btnName = "Login";
	
	$scope.error = false;
    $scope.success = false;
	
	$scope.login = function() {
		if ($scope.username == null) {
            alert("Please input Username");
        } 
        else if ($scope.password == null) {
            alert("Please input Password");
        }  
        else {
        	$scope.btnName = "Logging in...";
        	$scope.alert = "Checking Account. Please Wait...";
			
			$http({
				method: 'POST',
				url: 'login.php',
				data:{username:$scope.username, password:$scope.password}
			}).then(function (data){
				console.log(data)
				if(data.error){
					$scope.error = true;
					$scope.success = false;
					$scope.message = data.data.message;
            		setTimeout(function() {
            			$scope.btnName = "Login";
            			$scope.$apply();
  					}, 3000);
				}
				else{
					$scope.success = true;
					$scope.error = false;
					$scope.message = data.data.message;
            		setTimeout(function() {
	            		$scope.username = null;
	                	$scope.password = null;
	                	$scope.btnName = "Login";
	                	$scope.$apply();
	                }, 3000);
	                setTimeout(function() {	
            			window.location.reload();
            		}, 4000);
				}
				
			},function (error){
				console.log(error, 'can not get data.');
			});
        }
	}
});
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");
 
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
login.php
//login.php
<?php
	include('conn.php');
	session_start();
	$data = json_decode(file_get_contents("php://input"));
	
	$out = array('error' => false);
	$username = mysqli_real_escape_string($conn, $data->username);
    $password = mysqli_real_escape_string($conn, $data->password);
	
	$query=$conn->query("select * from tbluser where username='$username' and password='$password'");
    if($query->num_rows > 0){
		$row=$query->fetch_array();
		$_SESSION['user']=$row['id'];
        $out['message'] = "Login Successful. Username: $username Password: $password";
    }
    else{
        $out['error'] = true;
        $out['message'] = "Login Failed. User not Found!"; 
    }
  
    echo json_encode($out);
?>
home.php
//home.php
<?php
	session_start();
	if(!isset($_SESSION['user'])){
		header('location:index.php');
	}
	include('conn.php');
	$query=$conn->query("select * from tbluser where id='".$_SESSION['user']."'");
	$row=$query->fetch_array();
?>
<!DOCTYPE html>
<html>
<head>
<title>Angular JS PHP Mysql Login</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
</head>
<body>
<div class="container">
	<div class="row">
		<div class="col-md-6">
			<h2>Angular JS PHP Mysql Login</h2>
		</div>
	</div>
	<hr>
    <div class="row">
    	<div class="col-md-4">
    		<h2><center>Welcome, <?php echo $row['username']; ?></center></h2>
    		<center><a href="logout.php" class="btn btn-danger"> Logout</a></center>
    	</div>
    </div>
</div>
</body>
</html>
logout.php
//logout.php
<?php
	session_start();
	session_destroy();
	header('location:index.php');
?>
style.css
//style.css
body {
	background: #000 !important;
}
.card {
	border: 1px solid #28a745;
}
.card-login {
    margin-top:30px;
    padding: 18px;
    max-width: 30rem;
}

.card-header {
    color: #fff;
    /*background: #ff0000;*/
    font-family: sans-serif;
    font-size: 20px;
    font-weight: 600 !important;
    margin-top: 10px;
    border-bottom: 0;
}

.input-group-prepend span{
    width: 50px;
    background-color: #ff0000;
    color: #fff;
    border:0 !important;
}

input:focus{
    outline: 0 0 0 0  !important;
    box-shadow: 0 0 0 0 !important;
}

.login_btn{
    width: 130px;
}

.login_btn:hover{
    color: #fff;
    background-color: #ff0000;
}

.btn-outline-danger {
    color: #fff;
    font-size: 18px;
    background-color: #28a745;
    background-image: none;
    border-color: #28a745;
}

.form-control {
    display: block;
    width: 100%;
    height: calc(2.25rem + 2px);
    padding: 0.375rem 0.75rem;
    font-size: 1.2rem;
    line-height: 1.6;
    color: #28a745;
    background-color: transparent;
    background-clip: padding-box;
    border: 1px solid #28a745;
    border-radius: 0;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.input-group-text {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    padding: 0.375rem 0.75rem;
    margin-bottom: 0;
    font-size: 1.5rem;
    font-weight: 700;
    line-height: 1.6;
    color: #495057;
    text-align: center;
    white-space: nowrap;
    background-color: #e9ecef;
    border: 1px solid #ced4da;
    border-radius: 0;
}

AngularJS PHP Mysql Pagination

AngularJS PHP Mysql Pagination

angularjs CDN https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination

dirPagination libs Its very simple and easy to use

Database Table

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley ', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(6, 'Brielle', 'Williamson', 'New York'),
(7, 'Bruno', 'Nash', 'London'),
(8, 'Caesar', 'Vance', 'New York'),
(9, 'Cara', 'Stevens', 'New York'),
(10, 'Cedric', 'Kelly', 'Edinburgh');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS PHP Mysql Pagination</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="dirPaginate.js"></script>
</head>
<body>
<div class="container" ng-app="paginationApp" ng-controller="paginationController">
   <br />
    <h3 align="center">AngularJS PHP Mysql Pagination </h3>
    <br />
    <div class="table-responsive">
    <table class="table table-striped table-bordered">
		<thead>
		  <tr>
		   <th width="50">ID</th>
		   <th>Firts Name</th>
		   <th>Last Name</th>
		   <th>Address</th>
		  </tr>
		</thead>
		<tbody>
		  <tr dir-paginate="rs in allData|itemsPerPage:5">
		   <td>{{ rs.id }}</td>
		   <td>{{ rs.firstname }}</td>
		   <td>{{ rs.lastname }}</td>
		   <td>{{ rs.address }}</td>
		  </tr>
		</tbody>
    </table>
    </div>
    <div align="right">
		<dir-pagination-controls max-size="5" direction-links="true" boundary-links="true" >
		</dir-pagination-controls>
    </div>
</div>
<script>
var pagination_app = angular.module('paginationApp', ['angularUtils.directives.dirPagination']);
	pagination_app.controller('paginationController', function($scope, $http){
        $http({
            method: 'GET',
            url: 'fetch.php',
        }).then(function (data){
            console.log(data)
            $scope.allData = data.data;
        },function (error){
            console.log(error, 'can not get data.');
        });
	});
</script>
</body>
</html>
fetch.php
//fetch.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");
$query = "SELECT * FROM members ORDER BY id DESC";
$statement = $connect->prepare($query);
if($statement->execute())
{
	while($row = $statement->fetch(PDO::FETCH_ASSOC))
		{
		  $data[] = $row;
		}
	echo json_encode($data);
}
?>

AngularJS PHP MySQLi Pie Doughnut Chart using ChartJS

AngularJS PHP MySQLi Pie Doughnut Chart using ChartJS

angularjs CDN https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

Chart.js
chart.js is a simple, clean and engaging HTML5 based JavaScript charts. Chart.js is an easy way to include animated, interactive graphs on your website for free.

https://www.chartjs.org/

https://www.chartjs.org/docs/latest/

CREATE TABLE `productsales` (
  `saleid` int(11) NOT NULL,
  `productid` int(11) NOT NULL,
  `amount` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `productsales`
  ADD PRIMARY KEY (`saleid`);

ALTER TABLE `productsales`
  MODIFY `saleid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
  
  
CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `productname` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `products` (`id`, `productname`) VALUES
(1, 'Ipad'),
(2, 'Iphone'),
(3, 'Macbook'),
(4, 'Mac');

ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

index.html
//index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
	<title>AngularJS PHP MySQLi Pie Doughnut Chart using ChartJS</title>
	<meta charset="utf-8">
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
	
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
	
	<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
	<style type="text/css">
		canvas{
			margin:auto;
		}
		.alert{
			margin-top:20px;
		}
	</style>
</head>
<body ng-controller="myCtrl">
<div class="container">
	<div class="row"><h1>AngularJS PHP MySQLi Pie Doughnut Chart using ChartJS</h1>
		<div class="col-sm-3 col-md-offset-1" ng-init="fetchproducts()">
			<h3 class="page-header text-center">Add Purchase</h3>
			<div class="form-group">
				<label>Select Product:</label>
				<select ng-model="productid" class="form-control" name="productid">
					<option ng-repeat="rs in products" value="{{rs.id}}">{{rs.productname}}</option>
				</select>
			</div>
			<div class="form-group">
				<label>Amount:</label>
				<input type="text" class="form-control" name="amount" ng-model="amount">
			</div>
			<button type="button" ng-click="purchase()" class="btn btn-primary">Buy</button>
			<div class="alert alert-success text-center" ng-show="success">
				<button type="button" class="close" aria-hidden="true" ng-click="clear()">×</button>
				{{ message }}
			</div>
			<div class="alert alert-danger text-center" ng-show="error">
				<button type="button" class="close" aria-hidden="true" ng-click="clear()">×</button>
				{{ message }}
			</div>
		</div>
		<div class="col-sm-7" ng-init="fetchsales()">
			<h3 class="page-header text-center">Product Sales Chart</h3>
			<canvas id="dvCanvas" height="400" width="400"></canvas>
	    </div>
	</div>
</div>
<script>
var app = angular.module('app', []);
 
app.controller('myCtrl', function ($scope, $http) {
 
    $scope.error = false;
    $scope.success = false;
 
    $scope.fetchproducts = function(){
		$http({
            method: 'GET',
            url: 'fetchproducts.php',
        }).then(function (data){
            console.log(data)
            $scope.products = data.data;
        },function (error){
            console.log(error, 'can not get data.');
        });
    }
 
    $scope.purchase = function(){
		$http({
            method: 'POST',
            url: 'purchase.php',
			data:{amount:$scope.amount, productid:$scope.productid}
        }).then(function (data){
            console.log(data)
            if(data.error){
                $scope.error = true;
                $scope.success = false;
                $scope.message = data.data.message;
            }
            else{
                $scope.success = true;
                $scope.error = false;
                $scope.message = data.data.message;
                $scope.fetchsales();
                $scope.buy = '';
            }
        },function (error){
            console.log(error, 'can not get data.');
        });
    }
 
    //this fetches the data for our table
    $scope.fetchsales = function(){
		$http({
            method: 'GET',
            url: 'fetchsales.php',
        }).then(function (data){
            console.log(data)
            var ctx = document.getElementById("dvCanvas").getContext('2d');
            var myChart = new Chart(ctx, {
                type: 'pie', // change the value of pie to doughtnut for doughnut chart
                data: {
                    datasets: [{
                        data: data.data.total,
                        backgroundColor: ['blue', 'green', 'red', 'yellow']
                    }],
                    labels: data.data.productname
                },
                options: {
                    responsive: false
                }
            });
        },function (error){
            console.log(error, 'can not get data.');
        });
    }
 
    $scope.clear = function(){
        $scope.error = false;
        $scope.success = false;
    }
 
});
</script>
</body>
</html>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
fetchproducts.php
//fetchproducts.php
<?php
include('dbcon.php');

$out = array();
 
$sql = "SELECT * FROM products";
$query = $conn->query($sql);
 
while($row=$query->fetch_array()){
	$out[] = $row;
}
echo json_encode($out);
?>
purchase.php
//purchase.php
<?php
	include('dbcon.php');
 
	$out = array('error' => false);
 
	$data = json_decode(file_get_contents("php://input"));
 
	$productid = $data->productid;
	$amount = $data->amount;
 
	$sql = "INSERT INTO productsales (productid, amount) VALUES ('$productid', '$amount')";
	$query = $conn->query($sql);
 
	if($query){
		$out['message'] = "Purchase added successfully";
	}
	else{
		$out['error'] = true;
		$out['message'] = "Cannot add purchase"; 
	}
 
	echo json_encode($out);
?>
fetchsales.php
//fetchsales.php
<?php
	include('dbcon.php');
 
	$out = array();
 
	$sql = "SELECT *, sum(amount) AS total FROM productsales LEFT JOIN products ON products.id=productsales.productid GROUP BY productsales.productid";
	$query = $conn->query($sql);
 
	while($row=$query->fetch_array()){
	    $out['total'][] = $row['total'];
	    $out['productname'][] = $row['productname'];
	}
 
	echo json_encode($out);
?>

Thursday, December 23, 2021

AngularJS 1.8.2 Live Data Search with PHP Mysql and bootstrap

AngularJS 1.8.2 Live Data Search with PHP Mysql and bootstrap

https://angularjs.org/ version 1.8.2

CDN : https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

Bootstrap
https://getbootstrap.com/docs/4.3/getting-started/introduction/

Database Table

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`) VALUES
(1, 'Tiger Wood', 'Accountant', 'Tokyo', 36, 5689),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654),
(5, 'Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465),
(6, 'Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456),
(9, 'Airi Satou updated', 'Pre-Sales Support updated', 'New York', 25, 4568),
(10, 'Angelica Ramos updated', 'Sales Assistant updated', 'New York', 45, 456),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545),
(19, 'Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468),
(20, 'Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646),
(21, 'Shad Decker', 'Regional Director', 'Tokyo', 45, 4545);

ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
index.php
//index.php
<!DOCTYPE html>
<html>
 <head>
  <title>AngularJS Live Data Search with PHP Mysql and bootstrap</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div class="container" ng-app="angularlivesearch" ng-controller="search_controller" ng-init="fetchData()">
	<br />
	<h3 align="center">AngularJS 1.8.2 Live Data Search with PHP Mysql and bootstrap</h3>
	<br />
	<div class="form-group">
		<div class="input-group">
		 <input type="text" name="search_query" ng-model="search_query" ng-keyup="fetchData()" placeholder="Search" class="form-control" />
		</div>
	</div>
	<br />
	<table class="table table-striped table-bordered">
		<thead>
		 <tr>
		  <th>Name</th>
		  <th>Position</th>
		  <th>office</th>
		  <th>age</th>
		  <th>Salary</th>
		 </tr>
		</thead>
		<tbody>
		 <tr ng-repeat="data in searchData">
		  <td>{{ data.name }}</td>
		  <td>{{ data.position }}</td>
		  <td>{{ data.office }}</td>
		  <td>{{ data.age }}</td>
		  <td>{{ data.salary }}</td>
		 </tr>
		</tbody>
	</table>
</div>
  
<script>
var app = angular.module('angularlivesearch', []);
	app.controller('search_controller', function($scope, $http){
	$scope.fetchData = function(){
		$http({
            method: 'POST',
            url: 'fetch.php',
			data:{search_query:$scope.search_query}
        }).then(function (data){
            console.log(data)
            $scope.searchData = data.data;
        },function (error){
            console.log(error, 'can not get data.');
        });
	};
});
</script>
</body>
</html>
fetch.php
//fetch.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");

$form_data = json_decode(file_get_contents("php://input"));

$query = '';
$data = array();

if(isset($form_data->search_query))
{
	$search_query = $form_data->search_query;
	 $query = "
	 SELECT * FROM employee 
	 WHERE (name LIKE '%$search_query%' 
	 OR position LIKE '%$search_query%' 
	 OR office LIKE '%$search_query%') 
	";
}else{
	$query = "SELECT * FROM employee ORDER BY name ASC";
}

$statement = $connect->prepare($query);

if($statement->execute())
{
	while($row = $statement->fetch(PDO::FETCH_ASSOC))
	{
	  $data[] = $row;
	}
	 echo json_encode($data);
}
?>

AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)

AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)

https://angularjs.org/ version 1.8.2

CDN : https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

Database Table

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley ', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(6, 'Brielle', 'Williamson', 'New York'),
(7, 'Bruno', 'Nash', 'London'),
(8, 'Caesar', 'Vance', 'New York'),
(9, 'Cara', 'Stevens', 'New York'),
(10, 'Cedric', 'Kelly', 'Edinburgh');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
index.html
//index.html
<html>  
<head>  
<title>AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>  
<body>  
<div class="container"><br />
    <h3 align="center">AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)</h3><br />
    <div class="table-responsive" ng-app="angularinlinetablecrud" ng-controller="liveController" ng-init="fetchData()">
                <div class="alert alert-success alert-dismissible" ng-show="success" >
                    <a href="#" class="close" data-dismiss="alert" ng-click="closeMsg()" aria-label="close">×</a>
                    {{successMessage}}
                </div>
                <form name="testform" ng-submit="insertData()">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Address</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="text" ng-model="addData.firstname" class="form-control" placeholder="Enter First Name" ng-required="true" /></td>
                                <td><input type="text" ng-model="addData.lastname" class="form-control" placeholder="Enter Last Name" ng-required="true" /></td>
                                <td><input type="text" ng-model="addData.address" class="form-control" placeholder="Enter Address" ng-required="true" /></td>
                                <td><button type="submit" class="btn btn-success btn-sm" ng-disabled="testform.$invalid">Add</button></td>
                            </tr>
                            <tr ng-repeat="data in namesData" ng-include="getTemplate(data)">
                            </tr>
                            
                        </tbody>
                    </table>
                </form>
                <script type="text/ng-template" id="display">
                    <td>{{data.firstname}}</td>
                    <td>{{data.lastname}}</td>
                    <td>{{data.address}}</td>
                    <td>
                        <button type="button" class="btn btn-primary btn-sm" ng-click="showEdit(data)">Edit</button>
                        <button type="button" class="btn btn-danger btn-sm" ng-click="deleteData(data.id)">Delete</button>
                    </td>
                </script>
                <script type="text/ng-template" id="edit">
                    <td><input type="text" ng-model="formData.firstname" class="form-control"  /></td>
                    <td><input type="text" ng-model="formData.lastname" class="form-control" /></td>
                    <td><input type="text" ng-model="formData.address" class="form-control" /></td>
                    <td>
                        <input type="hidden" ng-model="formData.data.id" />
                        <button type="button" class="btn btn-info btn-sm" ng-click="editData()">Save</button>
                        <button type="button" class="btn btn-default btn-sm" ng-click="reset()">Cancel</button>
                    </td>
                </script>   

				<!--<div id="output">{{ foo }}</div> -->
   </div>  
  </div>
<script>
var app = angular.module('angularinlinetablecrud', []);

app.controller('liveController', function($scope, $http){

    $scope.formData = {};
    $scope.addData = {};
    $scope.success = false;

    $scope.getTemplate = function(data){ //alert(data.id);
        if (data.id === $scope.formData.id)
        {
            return 'edit';
        }
        else
        {
            return 'display';
        }
    };

    $scope.fetchData = function(){
		   $http({
			  method: 'GET',
			  url: 'select.php'
		   }).then(function (data){
				console.log(data)
				$scope.namesData = data.data;
				//$scope.foo = data.data;
		   },function (error){
				console.log(error, 'can not get data.');
		   });
    };

    $scope.insertData = function(){
        $http({
            method:"POST",
            url:"insert.php",
            data:$scope.addData,
        }).then(function(data){ alert(data.data.message);
            $scope.success = true;
            $scope.successMessage = data.data.message;
            $scope.fetchData();
            $scope.addData = {};
        });
    };

    $scope.showEdit = function(data) {
        $scope.formData = angular.copy(data);
    };

    $scope.editData = function(){
        $http({
            method:"POST",
            url:"edit.php",
            data:$scope.formData,
        }).then(function(data){
            $scope.success = true;
            $scope.successMessage = data.data.message;
            $scope.fetchData();
            $scope.formData = {};
        });
    };

    $scope.reset = function(){
        $scope.formData = {};
    };

    $scope.closeMsg = function(){
        $scope.success = false;
    };

    $scope.deleteData = function(id){
        if(confirm("Are you sure you want to remove it?"))
        {
            $http({
                method:"POST",
                url:"delete.php",
                data:{'id':id}
            }).then(function(data){
                $scope.success = true;
                $scope.successMessage = data.data.message;
                $scope.fetchData();
            }); 
        }
    };

});
</script>
</body>  
</html>  
db.php
//db.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");
?>
select.php
//select.php
<?php  
include('db.php');

$query = "SELECT * FROM members ORDER BY id DESC";
$statement = $connect->prepare($query);
if($statement->execute())
{
  while($row = $statement->fetch(PDO::FETCH_ASSOC))
  {
    $data[] = $row;
  }
  echo json_encode($data);
}
?>
insert.php
//insert.php
<?php  
include('db.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$data = array(
 ':firstname'  => $form_data->firstname,
 ':lastname'  => $form_data->lastname,
 ':address'  => $form_data->address
);

$query = "
 INSERT INTO members 
 (firstname, lastname, address) VALUES 
 (:firstname, :lastname, :address)
";

$statement = $connect->prepare($query);

if($statement->execute($data))
{
 $message = 'Data Inserted';
}

$output = array(
 'message' => $message
);

echo json_encode($output);
?>
edit.php
//edit.php
<?php  
include('db.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$data = array(
 ':firstname'  => $form_data->firstname,
 ':lastname'  => $form_data->lastname,
 ':address'  => $form_data->address,
 ':id'    => $form_data->id
);

$query = "
 UPDATE members 
 SET firstname = :firstname, lastname = :lastname , address = :address 
 WHERE id = :id
";

$statement = $connect->prepare($query);
if($statement->execute($data))
{
 $message = 'Data Edited';
}

$output = array(
 'message' => $message
);

echo json_encode($output);
?>
delete.php
//delete.php
<?php
include('db.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$query = "DELETE FROM members WHERE id = '".$form_data->id."'";

$statement = $connect->prepare($query);
if($statement->execute())
{
 $message = 'Data Deleted';
}

$output = array(
 'message' => $message
);

echo json_encode($output);
?>

Tuesday, December 21, 2021

ReactJS Load More Pagination Results

ReactJS Load More Pagination Results

Bootstrap : https://react-bootstrap.github.io/getting-started/introduction/

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

API call https://reqres.in/ 

https://reqres.in/api/users?per_page=2&page=1

{"page":1,"per_page":2,"total":12,"total_pages":6,"data":[{"id":1,"email":"george.bluth@reqres.in","first_name":"George","last_name":"Bluth","avatar":"https://reqres.in/img/faces/1-image.jpg"},{"id":2,"email":"janet.weaver@reqres.in","first_name":"Janet","last_name":"Weaver","avatar":"https://reqres.in/img/faces/2-image.jpg"}],"support":{"url":"https://reqres.in/#support-heading","text":"To keep ReqRes free, contributions towards server costs are appreciated!"}}

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'
import './index.css';
import 'bootstrap/dist/css/bootstrap.min.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { useEffect, useState } from 'react';

function App() {
  const perPage = 2;
  const [totalPages, setTotalPages] = useState(1);
  const [page, setPage] = useState(1);

  const [userList, setUserList] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const getUserList = () => {
      setLoading(true);
      fetch(`https://reqres.in/api/users?per_page=${perPage}&page=${page}`)
        .then(res => res.json())
        .then(res => {
          setTotalPages(res.total_pages);
          setUserList([...userList, ...res.data]);
          setLoading(false);
        });
    }
    getUserList();
  }, [page]);

  return (
    <div className="container" style={{padding: 20}}>
		<div className="row">
			<div className="col-3"></div>
			<div class="col-6">
				<h3>ReactJS Load More Pagination Results</h3>
				{userList.map((x, i) => {
					return <div key={i} className="box">
					<img src={x.avatar} />
					<div className="name">{x.first_name} {x.last_name}</div>
					<div className="email">{x.email}</div>
					</div>
				})}
				<div className="clearfix"></div>
				{totalPages !== page && <button className="btn btn-primary" onClick={() => setPage(page + 1)}>{loading ? 'Loading...' : 'Load More'}</button>}
			</div>
			<div className="col-3"></div>
		</div>
	</div>
  );
}

export default App;
src/index.css
//src/index.css
.box {
  float: left;
  width: 200px;margin-right:20px;margin-bottom:20px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background: #f5f5f5;
  padding-bottom: 10px;
}

.box img {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.box .name {
  padding: 10px 10px 5px 10px;
}

.box .email {
  font-style: italic;padding-left:10px;
  color: #666;
}

.clearfix {
  clear: both;margin-bottom:20px;
}

Sunday, December 19, 2021

Android Java Dialog Box App Version Name and Version Code

Android Java Dialog Box App Version Name and Version Code

app/src/main/res/layout/activity_main.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"
    tools:context=".MainActivity">

    <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/dialogbox"
        android:textSize="24sp" tools:text="Dialog Box" tools:textAlignment="center" />

    <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="bottom"
        android:orientation="vertical">

        <Button android:id="@+id/btnabout" android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" android:text="@string/aboutapp" />
    </LinearLayout>
</LinearLayout>
app/src/main/java/com/myappdev/MainActivity.Java
 
package com.myappdev;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button buttonAboutMe = (Button)findViewById(R.id.btnabout);

        buttonAboutMe.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View v) {

                String strVersion;

                PackageInfo packageInfo;
                try {
                    packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
                    strVersion = "Version Name: " + packageInfo.versionName +"\n"
                            + "Version Code: " + String.valueOf(packageInfo.versionCode);
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                    strVersion = "Cannot load Version!";
                }

                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("About The App!").setMessage(strVersion)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {}
                                }).show();
            }
        });
    }
}
app/src/main/res/value/strings.xml
 
<resources>
    <string name="app_name">MyappDev</string>
    <string name="app_first_started">App first started</string>
    <string name="aboutapp">- About -</string>
    <string name="dialogbox">Dialog Box</string>
</resources>

Android Java AutoCompleteTextView

Android Java AutoCompleteTextView

App/src/main/res/layout/activity_main.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android Java MultiAutoCompleteTextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <MultiAutoCompleteTextView android:id="@+id/multiautocompletetextview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="1"
        />
</LinearLayout>
app/src/main/java/com/myappdev/MainActivity.Java
 
package com.myappdev;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.MultiAutoCompleteTextView;

public class MainActivity extends AppCompatActivity {

    MultiAutoCompleteTextView myMultiAutoCompleteTextView;
    String item[]={
            "January", "February", "March", "April",
            "May", "June", "July", "August",
            "September", "October", "November", "December"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MultiAutoCompleteTextView myMultiAutoCompleteTextView
                = (MultiAutoCompleteTextView)findViewById(
                R.id.multiautocompletetextview);

        myMultiAutoCompleteTextView.setAdapter(
                new ArrayAdapter<String>(this,
                        android.R.layout.simple_dropdown_item_1line, item));
        myMultiAutoCompleteTextView.setTokenizer(
                new MultiAutoCompleteTextView.CommaTokenizer());
    }
}

Friday, December 17, 2021

PHP Mysql PDO CRUD (Create, Read, Update and Delete) Server Side Ajax Boostrap data table and Modal Form

PHP Mysql PDO CRUD (Create, Read, Update and Delete) Server Side Ajax Boostrap data table and Modal Form

Bootstrap Datatable Server-side processing https://datatables.net/examples/server_side/simple.html

Bootstrap Modal https://getbootstrap.com/docs/4.0/components/modal/

Database Table
CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley ', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(6, 'Brielle', 'Williamson', 'New York'),
(7, 'Bruno', 'Nash', 'London'),
(8, 'Caesar', 'Vance', 'New York'),
(9, 'Cara', 'Stevens', 'New York'),
(10, 'Cedric', 'Kelly', 'Edinburgh'),
(11, 'Charde', 'Marshall', 'San Francisco');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
index.php
//index.php
<!doctype html>
<head>
    <title>PHP Mysql PDO CRUD (Create, Read, Update and Delete) Server Side Ajax Boostrap data table and Modal Form</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.js"></script>
    
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container"> 
	<div class="row">
		<div class="col-3"></div>
		<div class="col-6">
		<h1>PHP Mysql PDO CRUD (Create, Read, Update and Delete) Server Side Ajax Boostrap data table and Modal Form</h1>                    
        <table id="member_table" class="table table-striped">  
            <thead>
                <tr class="table-primary">
                    <th width="5%">ID</th>
                    <th width="50%">First Name</th>  
                    <th width="50%">Last Name</th>
                    <th width="50%">Address</th>
                    <th scope="col" width="5%">Edit</th>
                    <th scope="col" width="5%">Delete</th>
                </tr>
            </thead>
        </table>
        </br>
        <div align="right">
            <button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-success btn-lg">Add New Member</button>
        </div>
		</div>
		<div class="col-3"></div>
	</div>	
	<div id="userModal" class="modal fade">
		<div class="modal-dialog">
			<form method="post" id="member_form" enctype="multipart/form-data">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal">×</button>
						<h4 class="modal-title">Add Member</h4>
					</div>
					<div class="modal-body">
						<label>Enter First Name</label>
						<input type="text" name="firstname" id="firstname" class="form-control" />
						<br />
						<label>Enter Last Name</label>
						<input type="text" name="lastname" id="lastname" class="form-control" />
						<br /> 						
						<label>Enter Address</label>
						<input type="text" name="address" id="address" class="form-control" />
						<br /> 
					</div>
					<div class="modal-footer">
						<input type="hidden" name="member_id" id="member_id" />
						<input type="hidden" name="operation" id="operation" />
						<input type="submit" name="action" id="action" class="btn btn-primary" value="Add" />
						<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</div> 
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
    $('#add_button').click(function(){
        $('#member_form')[0].reset();
        $('.modal-title').text("Add Member Details");
        $('#action').val("Add");
        $('#operation').val("Add");
    });
    
    var dataTable = $('#member_table').DataTable({
        "paging":true,
        "processing":true,
        "serverSide":true,
        "order": [],
        "info":true,
        "ajax":{
            url:"fetch.php",
            type:"POST"
               },
        "columnDefs":[
            {
                "targets":[0,3,4],
                "orderable":false,
            },
        ],    
    });

    $(document).on('submit', '#member_form', function(event){
        event.preventDefault();
        var id = $('#id').val();
        var firstname = $('#firstname').val();
        var lastname = $('#lastname').val();
        var address = $('#address').val();
        
        if(firstname != '' && lastname != '' && address != '')
        {
            $.ajax({
                url:"insert.php",
                method:'POST',
                data:new FormData(this),
                contentType:false,
                processData:false,
                success:function(data)
                {
                    $('#member_form')[0].reset();
                    $('#userModal').modal('hide');
                    dataTable.ajax.reload();
                }
            });
        }
        else
        {
            alert("Member First Name, Last Name Fields are Required");
        }
    });
    
    $(document).on('click', '.update', function(){
        var member_id = $(this).attr("id"); alert(member_id);
        $.ajax({
            url:"fetch_single.php",
            method:"POST",
            data:{member_id:member_id},
            dataType:"json",
            success:function(data)
            {
                $('#userModal').modal('show');
                $('#id').val(data.id);
                $('#firstname').val(data.firstname);
                $('#lastname').val(data.lastname);
                $('#address').val(data.address);
                $('.modal-title').text("Edit Member Details");
                $('#member_id').val(member_id);
                $('#action').val("Save");
                $('#operation').val("Edit");
            }
        })
    });
    
    $(document).on('click', '.delete', function(){
        var member_id = $(this).attr("id");
        if(confirm("Are you sure you want to delete this member?"))
        {
            $.ajax({
                url:"delete.php",
                method:"POST",
                data:{member_id:member_id},
                success:function(data)
                {
                    dataTable.ajax.reload();
                }
            });
        }
        else
        {
            return false;   
        }
    });
    
    
});
</script>              
</body>
</html>
db.php
//db.php
<?php
$connection = new PDO( 'mysql:host=localhost;dbname=testingdb', 'root', '' );
?>
insert.php
//insert.php
<?php
include('db.php');
include('function.php');
if(isset($_POST["operation"]))
{
	if($_POST["operation"] == "Add")
	{
		$statement = $connection->prepare("
			INSERT INTO members (firstname, lastname, address) VALUES (:firstname, :lastname, :address)");
		$result = $statement->execute(
			array(
				':firstname'	=>	$_POST["firstname"],
				':lastname'	=>	$_POST["lastname"],
				':address'	=>	$_POST["address"]
			)
		);
	}
	if($_POST["operation"] == "Edit")
	{
		$statement = $connection->prepare(
			"UPDATE members
			SET firstname = :firstname, lastname = :lastname, address = :address WHERE id = :id");
		$result = $statement->execute(
			array(
				':firstname'	=>	$_POST["firstname"],
				':lastname'	=>	$_POST["lastname"],
				':address'	=>	$_POST["address"],
				':id'			=>	$_POST["member_id"]
			)
		);
	}
}

?>
fetch.php
//fetch.php
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM members ";
if(isset($_POST["search"]["value"]))
{
	$query .= 'WHERE firstname LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR lastname LIKE "%'.$_POST["search"]["value"].'%" ';
}

if(isset($_POST["order"]))
{
	$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
	$query .= 'ORDER BY id ASC ';
}

if($_POST["length"] != -1)
{
	$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
} 
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
	$sub_array = array();
	
	$sub_array[] = $row["id"];
	$sub_array[] = $row["firstname"];
	$sub_array[] = $row["lastname"];                                                                              
	$sub_array[] = $row["address"];                                                                              //https://getbootstrap.com/docs/3.3/components/
	$sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-primary btn-sm update"><i class="glyphicon glyphicon-pencil"> </i>Edit</button></button>';
	$sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-sm delete"><i class="glyphicon glyphicon-remove">  Delete</button>';
	$data[] = $sub_array;
}
$output = array(
	"draw"				=>	intval($_POST["draw"]),
	"recordsTotal"		=> 	$filtered_rows,
	"recordsFiltered"	=>	get_total_all_records(),
	"data"				=>	$data
);
echo json_encode($output);
?>
function.php
//function.php
<?php
function get_total_all_records()
{
	include('db.php');
	$statement = $connection->prepare("SELECT * FROM members");
	$statement->execute();
	$result = $statement->fetchAll();
	return $statement->rowCount();
}
?>
fetch_single.php
//fetch_single.php
<?php
include('db.php');
include('function.php');
if(isset($_POST["member_id"]))
{
	$output = array();
	$statement = $connection->prepare(
		"SELECT * FROM members WHERE id = '".$_POST["member_id"]."' LIMIT 1"
	);
	$statement->execute();
	$result = $statement->fetchAll();
	foreach($result as $row)
	{
		$output["id"] = $row["id"];
		$output["firstname"] = $row["firstname"];
		$output["lastname"] = $row["lastname"];
		$output["address"] = $row["address"];
	}
	echo json_encode($output);
}
?>
delete.php
//delete.php
<?php
include('db.php');
include('function.php');

if(isset($_POST["member_id"]))
{
	$statement = $connection->prepare(
		"DELETE FROM members WHERE id = :id"
	);
	$result = $statement->execute(

		array(':id'	=>	$_POST["member_id"])
		
	);
}
?>

Thursday, December 16, 2021

AngularJS User Registraion Form

AngularJS User Registraion Form

AngularJS CDN https://angularjs.org/ https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

registraion.html
//registraion.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AngularJS User Registraion Form</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  </head>
<body>
	<div ng-app = "registrationform" class = "container">
	  <div style="text-align:center;color:blue">
		<h3><b>AngularJS User Registraion Form</b></h3>
	  </div>
		<div ng-controller = "FormController">
		  <div align="right">
			<a href="#" ng-click="searchUser()">{{title}}</a>
		  </div>
		  <form role = "form" class="well" ng-hide="ifSearchUser">
			<div class = "form-group">
				<label for = "name"> Name:  </label>
				<input type = "text" id = "name" class = "form-control" placeholder = "Enter Name " ng-model = "newcontact.name">
			</div>
			<div class = "form-group">
				<label for = "email"> Email:  </label>
				<input type = "email" id = "email" class = "form-control" placeholder = "Enter Email " ng-model = "newcontact.email">
			</div>
			<div class = "form-group">
				<label for = "password"> Password:  </label>
				<input type = "password" id = "password" class = "form-control" placeholder = "Enter Password " ng-model = "newcontact.password">
			</div>
			<div class = "form-group">
				<label for = "phone"> Phone:  </label>
				<input type = "text" id = "phone" class = "form-control" placeholder = "Enter Phone " ng-model = "newcontact.phone">
			</div>
			<br>
			<input type="hidden" ng-model="newcontact.id">
			<input type="button" class="btn btn-primary" ng-click="saveContact()" class="btn btn-primary" value = "Submit">
		  </form>
			
		  <div><h4><b>Registered Users</b></h4>
			<table ng-if="contacts.length" class = "table table-striped table-bordered table-hover">
			  <thead>
				<tr class = "info">
					<th>Name</th>
					<th>Email</th>
					<th>Phone</th>
					<th ng-if="!ifSearchUser">Action</th>
				</tr>
				</thead>
				<tbody>
				<tr ng-repeat = "contact in contacts">
					 <td>{{ contact.name }}</td>
					 <td>{{ contact.email }}</td>
					 <td>{{ contact.phone }}</td>
	
					 <td ng-if="!ifSearchUser">
						<a href="#" ng-click="edit(contact.id)" role = "button" class = "btn btn-info">edit</a>  
						<a href="#" ng-click="delete(contact.id)" role = "button" class = "btn btn-danger">delete</a>
					</td>
				</tr>
				</tbody>
			</table>
		  <div ng-hide="contacts.length > 0">No Users Found</div>
		  </div>
		</div>
	</div>
<script>
var myApp = angular.module("registrationform", []);
myApp.service("ContactService" , function(){
	var uid = 1;
	var contacts = [{
		  'id' : 0,
				 'name' : 'Cairocoders Ednalan',
				 'email' : 'cairocoders@gmail.com',
				 'password': '123456',
				 'phone' : '123456789'}, {
		  'id' : 2,
				 'name' : 'clydey Ednalan',
				 'email' : 'clyde@gmail.com',
				 'password': '123456',
				 'phone' : '123456789'}];	
	
	this.save = function(contact)  
	{
		if(contact.id == null)                       
		{
			contact.id = uid++;
			contacts.push(contact);
		}
		else
		{
			for(var i in contacts)
			{
				if(contacts[i].id == contact.id)
				{
					contacts[i] = contact;
				}
			}
		}
	};
	
	this.get = function(id)
	{
		for(var i in contacts )
		{
			if( contacts[i].id == id)
			{
				return contacts[i];
			}
		}
	};
	
	//Delete a contact
	this.delete = function(id)
	{
		for(var i in contacts)
			{
				if(contacts[i].id == id)
				{
					contacts.splice(i,1);
				}
			}
	};	
	//Show all contacts
	this.list = function()
	{
		return contacts;
	}	;	
});
	
myApp.controller("FormController" , function($scope , ContactService){
    console.clear();
    
    $scope.ifSearchUser = false;
    $scope.title ="List of Users";
    
		$scope.contacts = ContactService.list();
		
		$scope.saveContact = function()
		{
		  console.log($scope.newcontact);
		  if($scope.newcontact == null || $scope.newcontact == angular.undefined)
		  return;
			ContactService.save($scope.newcontact);
			$scope.newcontact = {};
		};		
		$scope.delete = function(id)
		{
			ContactService.delete(id);
			if($scope.newcontact != angular.undefined && $scope.newcontact.id == id)
				{
					$scope.newcontact = {};
				}
		};		
		$scope.edit = function(id)
		{
			$scope.newcontact = angular.copy(ContactService.get(id));
		};		
		$scope.searchUser = function(){
		  if($scope.title == "List of Users"){
		    $scope.ifSearchUser=true;
		    $scope.title = "Back";
		  }
		  else
		  {
		    $scope.ifSearchUser = false;
		    $scope.title = "List of Users";
		  }		  
		};
});
</script>	
</body>
</html>

Related Post