article

Friday, February 11, 2022

Vue.js PHP Input Validation

Vue.js PHP Input Validation

Bootstrap 4.0 Version
https://getbootstrap.com/docs/4.0/getting-started/introduction/
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css

vuejs
https://v2.vuejs.org/v2/guide/installation.html
CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

Axios  
https://www.npmjs.com/package/axios
CDN : https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>Vue.js PHP Input Validation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light navbar-cairocoders">
    <div class="container">
    <a class="navbar-brand" href="#">Cairocoders</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" href="#">Login</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Register</a>
            </li>
        </ul>

    </div>
    </div>
</nav>

<main class="my-form" id="validate">
    <div class="cotainer">
        <div class="row justify-content-center">
            <div class="col-md-8"><h1 class="page-header text-center">Vue.js PHP Input Validation </h1>
                    <div class="card">
                        <div class="card-header">Register</div>
                        <div class="card-body">
						
							<div class="alert alert-success text-center" v-if="successMessage">
								<button type="button" class="close" @click="clearMessage();"><span aria-hidden="true">×</span></button>
								<span class="glyphicon glyphicon-check"></span> {{ successMessage }}
							</div>
                           
                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Username</label>
                                    <div class="col-md-6">
                                        <input type="text" ref="username" class="form-control" v-model="forValidation.username">
										<div v-if="errorUsername" class="error">{{ errorUsername }}</div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Password</label>
                                    <div class="col-md-6">
                                        <input type="password" ref="password" class="form-control" v-model="forValidation.password">
										<div v-if="errorPassword" class="error">{{ errorPassword }}</div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Firstname</label>
                                    <div class="col-md-6">
                                        <input type="text" ref="firstname" class="form-control" v-model="forValidation.firstname">
										<div v-if="errorFirstname" class="error">{{ errorFirstname }}</div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Lastname</label>
                                    <div class="col-md-6">
                                        <input type="text" ref="lastname" class="form-control" v-model="forValidation.lastname">
										<div v-if="errorLastname" class="error">{{ errorLastname }}</div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Email</label>
                                    <div class="col-md-6">
                                        <input type="text" ref="email" class="form-control" v-model="forValidation.email">
										<div v-if="errorEmail" class="error">{{ errorEmail }}</div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Website</label>
                                    <div class="col-md-6">
                                        <input type="text" ref="website" class="form-control" v-model="forValidation.website">
										<div v-if="errorWebsite" class="error">{{ errorWebsite }}</div>
                                    </div>
                                </div>

                                <div class="col-md-6 offset-md-4">
									<button class="btn btn-primary" @click="validateInput();"><span class="glyphicon glyphicon-check"></span> Validate</button>
                                </div>
                        </div>
                    </div>
            </div>
        </div>
    </div>
</div>
</main>
<script src="app.js"></script>
<style>
body{
    margin: 0;
    font-size: .9rem;
    font-weight: 400;
    line-height: 1.6;
    color: #212529;
    text-align: left;
    background-color: #f5f8fa;
}

.navbar-cairocoders
{
    box-shadow: 0 2px 4px rgba(0,0,0,.04);
}

.navbar-brand , .nav-link, .my-form, .login-form
{
    font-family: Raleway, sans-serif;
}

.my-form
{
    padding-top: 1.5rem;
    padding-bottom: 1.5rem;
}

.my-form .row
{
    margin-left: 0;
    margin-right: 0;
}

.login-form
{
    padding-top: 1.5rem;
    padding-bottom: 1.5rem;
}

.login-form .row
{
    margin-left: 0;
    margin-right: 0;
}
.error{
	font-size:13px;color:red;
}
</style>
</body>
</html>
app.js
//app.js
var app = new Vue({
	el: '#validate',
	data:{
		forValidation: {username: '', password: '', firstname:'', lastname:'', email:'', website:''},
		errorUsername: "",
		errorPassword: "",
		errorFirstname: "",
		errorLastname: "",
		errorEmail: "",
		errorWebsite: "",
		successMessage: ""
	},

	methods:{
		validateInput: function(){
			var valForm = app.toFormData(app.forValidation);
			axios.post('validate.php', valForm)
				.then(function(response){
					//console.log(response);
					if(response.data.username){
						app.errorUsername = response.data.message;
						app.focusUsername();
					}
					else if(response.data.password){
						app.errorPassword = response.data.message;
						app.errorUsername = '';
						app.focusPassword();
					}
					else if(response.data.firstname){
						app.errorFirstname = response.data.message;
						app.errorUsername = '';
						app.errorPassword = '';
						app.focuFirstname();
					}
					else if(response.data.lastname){
						app.errorLastname = response.data.message;
						app.errorUsername = '';
						app.errorPassword = '';
						app.errorFirstname = '';
						app.focusLastname();
					}
					else if(response.data.email){
						app.errorEmail = response.data.message;
						app.errorUsername = '';
						app.errorPassword = '';
						app.errorFirstname = '';
						app.errorLastname = '';
						app.focusEmail();
					}
					else if(response.data.website){
						app.errorWebsite = response.data.message;
						app.errorEmail = response.data.message;
						app.errorUsername = '';
						app.errorPassword = '';
						app.errorFirstname = '';
						app.errorLastname = '';
						app.errorEmail = '';
						app.focusWebsite();
					}
					else{
						app.successMessage = response.data.message;
						app.errorUsername = '';
						app.errorPassword = '';
						app.errorFirstname = '';
						app.errorLastname = '';
						app.errorEmail = '';
						app.errorWebsite = '';
					}
				});
		},

		focusUsername: function(){
			this.$refs.username.focus();
		},

		focusPassword: function(){
			this.$refs.password.focus();
		},

		focusFirstname: function(){
			this.$refs.firstname.focus();
		},

		focusLastname: function(){
			this.$refs.lastname.focus();
		},

		focusEmail: function(){
			this.$refs.email.focus();
		},

		focusWebsite: function(){
			this.$refs.website.focus();
		},

		toFormData: function(obj){
			var form_data = new FormData();
			for(var key in obj){
				form_data.append(key, obj[key]);
			}
			return form_data;
		},

		clearMessage: function(){
			app.successMessage = '';
		}

	}
});
validate.php
//validate.php
<?php

$out = array('username' => false, 'password' => false, 'firstname' => false, 'lastname' => false, 'email' => false, 'website' => false);

function check_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

$username=check_input($_POST['username']);
$password=check_input($_POST['password']);
$firstname=check_input($_POST['firstname']);
$lastname=check_input($_POST['lastname']);
$email=check_input($_POST['email']);
$website=check_input($_POST['website']);

if($username==''){
	$out['username']=true;
	$out['message']='Username is required';
}

elseif (!preg_match("/^[a-zA-Z_1-9]*$/",$username)) {
	$out['username']=true;
  	$out['message'] = "Only letters, numbers and underscore allowed"; 
}

elseif($password==''){
	$out['password']=true;
	$out['message']='Password is required';
}

elseif($firstname==''){
	$out['firstname']=true;
	$out['message']='Firstname is required';
}

elseif (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
	$out['firstname']=true;
  	$out['message'] = "Only letters and white space allowed"; 
}

elseif($lastname==''){
	$out['lastname']=true;
	$out['message']='Lastname is required';
}

elseif (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
	$out['lastname']=true;
  	$out['message'] = "Only letters and white space allowed"; 
}

elseif($email==''){
	$out['email']=true;
	$out['message']='Email is required';
}

elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  	$out['email']=true;
	$out['message']='Invalid Email Format';
}

elseif($website==''){
	$out['website']=true;
	$out['message']='Website is required';
}

elseif (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  	$out['website']=true;
	$out['message']='Invalid URL';
}

else{
	$out['message']='Form Validated';
}

header("Content-type: application/json");
echo json_encode($out);
die();

?>

SwiftUI Date and Time Picker

SwiftUI Date and Time Picker

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @State var currentTime = Date()
    var closedRange = Calendar.current.date(byAdding: .year, value: -1, to: Date())!
    
    func formatDate() -> String {
        let components = Calendar.current.dateComponents([.hour, .minute, .day, .month, .year], from: currentTime)
        let hour = components.hour ?? 0
        let minute = components.minute ?? 0
        let day = components.day ?? 0
        let month = components.month ?? 0
        let year = components.year ?? 0
        
        return "\(day)-\(month)-\(year) (\(hour):\(minute))"
    }
    
    
    var body: some View {
        Form {
            Section(header:(Text("Date Picker 1"))) {
                DatePicker("Pick a date:", selection: $currentTime) // Normal Date Time Picker
            }
            
            Section(header:(Text("Date Picker 2"))) {
                DatePicker("Pick a future date:", selection: $currentTime, in: Date()...) // Only pick a future date
            }
            
            Section(header:(Text("Date Picker 3"))) {
                DatePicker("Pick a past date:", selection: $currentTime, in: closedRange...Date(), displayedComponents: .date) // Only pick a past date
            }
            
            Section(header:(Text("Date Picker 4"))) {
                DatePicker("Pick a time:", selection: $currentTime, displayedComponents: .hourAndMinute)
            }
            
            Section(header:(Text("Result"))) {
                Text(formatDate())
            }
            
        }
    }
}

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

SwiftUI Splash Screen

SwiftUI Splash Screen

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.gray
                .ignoresSafeArea()
            Text("ContentView")
                .foregroundColor(.white)
                .font(.system(size: 20))
                .bold()
                .padding()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
SplashScreenView.swift
 
//
//  SplashScreenView.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI

struct SplashScreenView: View {
    @State var isActive : Bool = false
    @State private var size = 0.8
    @State private var opacity = 0.5
    
    var body: some View {
        if isActive {
            ContentView()
        } else {
            VStack {
                VStack {
                    Image("logo")
                        .resizable()
                        .scaledToFill()
                        .frame(width: 128, height: 128)

                    Text("Cairocoders")
                        .font(Font.custom("Baskerville-Bold", size: 26))
                        .foregroundColor(.black.opacity(0.80))
                }
                .scaleEffect(size)
                .opacity(opacity)
                .onAppear {
                    withAnimation(.easeIn(duration: 1.1)) {
                        self.size = 0.9
                        self.opacity = 1.00
                    }
                }
            }
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                    withAnimation {
                        self.isActive = true
                    }
                }
            }
        }
    }
}

struct SplashScreenView_Previews: PreviewProvider {
    static var previews: some View {
        SplashScreenView()
    }
}
swiftuidev15iosApp.swift
 
//
//  swiftuidev15iosApp.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI

@main
struct swiftuidev15iosApp: App {
    var body: some Scene {
        WindowGroup {
            SplashScreenView()
        }
    }
}

Tuesday, February 8, 2022

AngularJS PHP Mysql Add Dynamically Remove Input Fields

AngularJS PHP Mysql Add Dynamically Remove Input Fields

Bootstrap 4.0 Version
https://getbootstrap.com/docs/4.0/getting-started/introduction/
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css

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

Bootstrap Icons
https://icons.getbootstrap.com/#install
CDN : https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css

CREATE TABLE `tblprogramming` (
  `id` int(11) NOT NULL,
  `username` varchar(150) NOT NULL,
  `title` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `tblprogramming` (`id`, `username`, `title`) VALUES
(1, 'cairocoders', 'python, python flask, python django, python tkinter');

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

ALTER TABLE `tblprogramming`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS PHP Mysql Add Dynamically Remove Input Fields</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<h3 align="center">AngularJS PHP Mysql Add Dynamically Remove Input Fields </h3>
<br />
<div ng-app="appdynamicaddremove" ng-controller="CTRdynamicaddremove" class="container" style="width:600px;" ng-init="fetchData()">
   
	<div class="alert alert-success alert-dismissible" ng-show="success" >
		<a href="#" class="close" aria-label="close">×</a>
		{{successMessage}}
	</div>

	<div class="alert alert-danger alert-dismissible" ng-show="error" >
		<a href="#" class="close" aria-label="close">×</a>
		{{errorMessage}}
	</div>

	<form method="post" ng-submit="submitForm()">
		<div class="form-group">
			User Name : Cairocoders
		</div>
		<fieldset ng-repeat="row in rows">
			<div class="form-group">
				<label>Enter Your Programming Skill</label>
				<div class="row">
				   <div class="col-md-9">
						<input type="text" name="programming_languages[]" class="form-control" ng-model="formData.skill[$index + 1]" />
				   </div>
				   <div class="col-md-3">
						<button type="button" name="remove" ng-model="row.remove" class="btn btn-danger btn-sm" ng-click="removeRow()"><i class="bi bi-dash-square"></i></button>
				   </div>
				</div>
			</div>
		</fieldset>
		<div class="form-group">
		 <button type="button" name="add_more" class="btn btn-success" ng-click="addRow()"><i class="bi bi-plus-square"></i> Add</button>
		 <input type="submit" name="submit" class="btn btn-info" value="Save" />
		</div>
	</form>

   <div class="table-responsive">
		<table class="table table-bordered table-striped">
			<tr>
			  <th>Programming Languages</th>
			</tr>
			<tr ng-repeat="rs in skills">
			  <td>{{rs.title}}</td>
			</tr>
		</table>
   </div>
</div>
<script>
var app = angular.module('appdynamicaddremove', []);
app.controller('CTRdynamicaddremove', function($scope, $http){

	$scope.success = false;
	$scope.error = false;

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

	$scope.rows = [{name: 'programming_languages[]', name: 'remove'}];

	$scope.addRow = function(){
		var id = $scope.rows.length + 1;
		$scope.rows.push({'id':'dynamic'+id});
	};

	$scope.removeRow = function(row){
		var index = $scope.rows.indexOf(row);
		$scope.rows.splice(index, 1);
	};

	$scope.formData = {};

	$scope.submitForm = function(){
		$http({
			method: 'POST',
			url: 'insert.php',
			data:$scope.formData
		}).then(function (data){
			console.log(data)  
			   if(data.data.error != '')
			   {
				$scope.success = false;
				$scope.error = true;
				$scope.errorMessage = data.data.error;
			   }
			   else
			   {
				$scope.success = true;
				$scope.error = false;
				$scope.successMessage = data.data.message;
				$scope.formData = {};
				$scope.rows = [{name: 'programming_languages[]', name: 'remove'}];
				$scope.fetchData();
			   }
		},function (error){
			console.log(error, 'can not post data.');
		});
	};

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

$query = "SELECT * FROM tblprogramming ORDER BY id";
$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
$connect = new PDO('mysql:host=localhost;dbname=testingdb', 'root', '');

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

$error = '';
$message = '';
$validation_error = '';
$programming_languages = '';

if(empty($form_data->skill)){
	$error[] = 'Programming Language is Required';
}else{
	 foreach($form_data->skill as $language)
	 {
		$programming_languages .= $language . ', ';
	 }
	 $programming_languages = substr($programming_languages, 0, -2);
}

$data = array(
	':programming_languages' => $programming_languages
);

if(empty($error)) {
	$query = "
	INSERT INTO tblprogramming 
	 (username, title) VALUES 
	 ('cairocoders', :programming_languages)
	 ";
	 $statement = $connect->prepare($query);
	 if($statement->execute($data))
	 {
		$message = 'Data Inserted';
	 }
}else{
	$validation_error = implode(", ", $error);
}

$output = array(
	 'error'  => $validation_error,
	 'message' => $message
);
echo json_encode($output);
?>

AngularJS PHP Mysql Dynamic Dropdown List

AngularJS PHP Mysql Dynamic Dropdown List


Bootstrap 4.0 Version
https://getbootstrap.com/docs/4.0/getting-started/introduction/
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css

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

CREATE TABLE `countries` (
  `id` int(6) NOT NULL,
  `value` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `countries` (`id`, `value`) VALUES
(1, 'Afghanistan'),
(171, 'Philippines'),
(227, 'United States of America');

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

ALTER TABLE `countries`
  MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=228;
  
CREATE TABLE `state` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `country_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `state` (`id`, `name`, `country_id`) VALUES
(1, 'ARMM', 171),
(2, 'Bicol', 171),
(3, 'Central Luzon', 171),
(4, 'Central Mindanao', 171),
(5, 'Alabama', 227),
(6, 'Alaska', 227),
(7, 'Arizona', 227),
(8, 'California', 227),
(9, 'Florida', 227);

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

ALTER TABLE `state`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
index.html
//index.html
<!DOCTYPE html>  
<html>  
<head>  
<title>AngularJS PHP Mysql Dynamic Dropdown List</title>  
<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/4.0.0/css/bootstrap.min.css" />  
</head>  
<body>  
<div class="container" style="width:650px;">  
    <h3 align="center">AngularJS PHP Mysql Dynamic Dropdown List</h3>  
    <br />  
    <div ng-app="appdynamicdropdown" ng-controller="CTRdynamicdropdown" ng-init="loadCountry()">  
        <select name="country" ng-model="country" class="form-control" ng-change="loadState()">  
            <option value="">Select Country</option>  
            <option ng-repeat="country in countries" value="{{country.id}}">{{country.value}}</option>  
        </select>  
        <br />  
        <select name="state" ng-model="state" class="form-control">  
            <option value="">Select State</option>  
            <option ng-repeat="state in states" value="{{state.id}}">  
                {{state.name}}  
            </option>  
        </select>  
    </div>  
</div> 
<script>  
var app = angular.module("appdynamicdropdown",[]);  
app.controller("CTRdynamicdropdown", function($scope, $http){  
      $scope.loadCountry = function(){  
		$http({
			method: 'GET',
			url: 'load_country.php'
		}).then(function (data){
			console.log(data)  
			$scope.countries = data.data;  
		},function (error){
			console.log(error, 'can not get data.');
		});
      }  
	  
      $scope.loadState = function(){  
		$http({
			method: 'POST',
			url: 'load_state.php',
			data: { country_id: $scope.country }
		}).then(function (data){
			console.log(data)  
			$scope.states = data.data;   
		},function (error){
			console.log(error, 'can not post data.');
		}); 
      }  
 });  
</script> 		   
</body>  
</html>   
load_country.php
//load_country.php
<?php   
 $connect = mysqli_connect("localhost", "root", "", "testingdb");  
 $output = array();  
 $query = "SELECT * FROM countries ORDER BY value ASC";  
 $result = mysqli_query($connect, $query);  
 while($row = mysqli_fetch_array($result))  
 {  
    $output[] = $row;  
 }  
 echo json_encode($output);  
?>  
load_state.php
//load_state.php
<?php   
 $connect = mysqli_connect("localhost", "root", "", "testingdb");  
 $output = array();  
 $data = json_decode(file_get_contents("php://input"));  
 $query = "SELECT * FROM state WHERE country_id='".$data->country_id."' ORDER BY name ASC";  
 $result = mysqli_query($connect, $query);  
 while($row = mysqli_fetch_array($result))  
 {  
    $output[] = $row;  
 }  
 echo json_encode($output);  
?>

AngularJS Autocomplete Textbox

AngularJS Autocomplete Textbox

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

angularjs CDN
https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js
index.html
//index.html
<!DOCTYPE html>  
<html>  
<head>  
<title>AngularJS Autocomplete Textbox</title>  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/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" style="width:500px;margin-top:20px;">  
    <h3 align="center">AngularJS Autocomplete Textbox</h3>  
    <div ng-app="appautocomplete" ng-controller="CTRautocomplete">  
        <label>Enter Country Name</label>  
        <input type="text" name="country" id="country" ng-model="country" ng-keyup="complete(country)" class="form-control" />  
        <ul class="list-group" ng-model="hidethis" ng-hide="hidethis">  
            <li class="list-group-item" ng-repeat="countrydata in filterCountry" ng-click="fillTextbox(countrydata)">{{countrydata}}</li>  
        </ul>  
    </div>  
</div>  
<script>  
 var app = angular.module("appautocomplete",[]);  
 app.controller("CTRautocomplete", function($scope){  
      $scope.countryList = [  
           "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"  
      ];  
      $scope.complete = function(string){  
           $scope.hidethis = false;  
           var output = [];  
           angular.forEach($scope.countryList, function(country){  
                if(country.toLowerCase().indexOf(string.toLowerCase()) >= 0)  
                {  
                     output.push(country);  
                }  
           });  
           $scope.filterCountry = output;  
      }  
      $scope.fillTextbox = function(string){  
           $scope.country = string;  
           $scope.hidethis = true;  
      }  
 });  
</script>
<style>  
li{  
   cursor:pointer;  
}  
li:hover{  
    background-color:#f9f9f9;  
}  
</style> 
</body>  
</html>  

AngularJS PHP Mysql Submit Form Data

AngularJS PHP Mysql Submit Form Data

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

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

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;

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS PHP Mysql Submit Form Data</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/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" style="width:750px;">
    <h3 align="center">AngularJS PHP Mysql Submit Form Data</h3>
    <br /><br />
    <div ng-app="myapp" ng-controller="formcontroller">
    <form name="userForm" ng-submit="insertData()">
		<label class="text-success" ng-show="successInsert">{{successInsert}}</label>
		<div class="form-group">
			<label>First Name <span class="text-danger">*</span></label>
			<input type="text" name="first_name" ng-model="insert.first_name" class="form-control" />
			<span class="text-danger" ng-show="errorFirstname">{{errorFirstname}}</span>
		</div>
		<div class="form-group">
			<label>Last Name <span class="text-danger">*</span></label>
			<input type="text" name="last_name" ng-model="insert.last_name" class="form-control" />
			<span class="text-danger" ng-show="errorLastname">{{errorLastname}}</span>
		</div>
		<div class="form-group">
			<label>Address <span class="text-danger">*</span></label>
			<input type="text" name="address" ng-model="insert.address" class="form-control" />
			<span class="text-danger" ng-show="erroraddress">{{erroraddress}}</span>
		</div>
		<br />
		<div class="form-group">
			<input type="submit" name="insert" class="btn btn-info" value="Insert"/>
		</div>
    </form>
    </div>
</div>
  
<script>
var application = angular.module("myapp", []);
application.controller("formcontroller", function($scope, $http){
	$scope.insert = {};
	$scope.insertData = function(){
		$http({
			method: 'POST',
			url: 'insert.php',
			data:$scope.insert,
		}).then(function (data){
			console.log(data) 
			   if(data.data.error)
			   {
				$scope.errorFirstname = data.data.error.first_name;
				$scope.errorLastname = data.data.error.last_name;
				$scope.erroraddress = data.data.error.address;
				$scope.successInsert = null;
			   }
			   else
			   {
				$scope.insert = null;
				$scope.errorFirstname = null;
				$scope.errorLastname = null;
				$scope.erroraddress = null;
				$scope.successInsert = data.data.message;
			   } 
		},function (error){
			console.log(error, 'can not post data.');
		});
	}
});
</script>
</body>
</html>
insert.php
//insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testingdb");
$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();

if(empty($form_data->first_name))
{
	$error["first_name"] = "First Name is required";
}

if(empty($form_data->last_name))
{
	$error["last_name"] = "Last Name is required";
}

if(!empty($error))
{
	$data["error"] = $error;
}
else
{
	$first_name = mysqli_real_escape_string($connect, $form_data->first_name); 
	$last_name = mysqli_real_escape_string($connect, $form_data->last_name);
	$address = mysqli_real_escape_string($connect, $form_data->address);
	$query = "
	  INSERT INTO members(firstname, lastname, address) VALUES ('$first_name', '$last_name', '$address')
	";
	if(mysqli_query($connect, $query))
	{
	  $data["message"] = "Data Inserted...";
	}
}
echo json_encode($data);
?>

AngularJS Jquery Datatables with PHP Mysql

AngularJS Jquery Datatables with PHP Mysql

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

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

Jquery
https://jquery.com/download/

Other CDNs jsDelivr CDN : https://www.jsdelivr.com/package/npm/jquery 
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

https://datatables.net/
CDN version 1.11.4

Angular DataTables
https://github.com/l-lin/angular-datatables


index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Jquery Datatables with PHP Mysql</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="angular-datatables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.4/css/jquery.dataTables.min.css">
</head>
<body>
<div ng-app="Appdatatables" ng-controller="CTRdatatables" class="container">
	<br />
	<h3 align="center">AngularJS Jquery Datatables with PHP Mysql</h3>
	<br />
	<table datatable="ng" dt-options="vm.dtOptions" class="table table-striped table-bordered">
		<thead>
			<tr>
				<th>Sr</th>
				<th>First Name</th>
				<th>Last Name</th>
				<th>Address</th>
			</tr>
		</thead>
		<tbody>
			<tr ng-repeat="rs in members">
				<td>{{ $index + 1 }}</td>
				<td>{{ rs.firstname }}</td>
				<td>{{ rs.lastname }}</td>
				<td>{{ rs.address }}</td>
			</tr>
		</tbody>
	</table>
	<br />
	<br />
</div>
<script>
var app = angular.module('Appdatatables', ['datatables']);
app.controller('CTRdatatables', function($scope, $http){
	$http({
        method: 'GET',
        url: 'fetch.php',
    }).then(function (data){
        console.log(data) 
        $scope.members = 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);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
	$data[] = $row;
}
echo json_encode($data);
?>

AngularJS Show Password

AngularJS Show Password

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

https://icons.getbootstrap.com/
CDN : https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css

https://getbootstrap.com/docs/5.1/getting-started/introduction/
index.html
//index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AngularJS Show Password</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
</head>
<body>
<div id="login">
<div class="container" ng-app="appshowpassword" ng-controller="CTR_showpass">
   <br />
   <h2 align="center">AngularJS Show Password</h2><br />

    <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">
			<div class="panel-heading">
				<h3 class="panel-title">Login</h3>
			</div>
			<div class="panel-body">
				<div class="form-group">
				  <label>Enter Email</label>
				  <input type="text" name="email" class="form-control input-lg" ng-model="email_field" placeholder="Enter Email">
				</div>
				<div class="form-group">
					<label>Enter Password</label> 
					<div class="input-group">
						<input type="{{inputType}}" name="password" class="form-control input-lg" ng-model="password_field" placeholder="Enter Password" />
						<span class="{{showHideClass}}" ng-click="showPassword()" style="cursor:pointer"></span>
					</div>
				</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>
                    <input type="submit" name="submit" class="btn btn-info btn-lg" value="submit">
                </div>
			</div>
		</div>
   </div>
   </div>
</div>
</div>
<script>
var app = angular.module('appshowpassword', []);
app.controller('CTR_showpass', function($scope){

	$scope.inputType = 'password';
	$scope.showHideClass = 'input-group-text bi bi-eye-slash-fill';

	$scope.showPassword = function(){
		if($scope.password_field != null) {
			if($scope.inputType == 'password')
			{
				 $scope.inputType = 'text';
				 $scope.showHideClass = 'input-group-text bi bi-eye-fill'; 
			}
			else
			{
				 $scope.inputType = 'password';
				 $scope.showHideClass = 'input-group-text bi bi-eye-slash-fill';
			}
		}
	};

});
</script>
<style>
body {
  margin: 0;
  padding: 0;
  background-color: #17a2b8;
  height: 100vh;
}
#login .container #login-row #login-column #login-box {
  border: 1px solid #9C9C9C;
  background-color: #EAEAEA;
  padding: 20px;
}
#login .container #login-row #login-column #login-box #login-form {
  padding: 20px;
}
</style>
</body>
</html>

Monday, February 7, 2022

SwiftUI Firebase Login Register Log Out - Firebase Auth

SwiftUI Firebase Login Register Log Out - Firebase Auth

Firebase Apple Open Source Development
https://github.com/firebase/firebase-ios-sdk

SDWebImageSwiftUI
https://github.com/SDWebImage/SDWebImageSwiftUI


ContentView.swift
 
//
//  ContentView.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI
import Firebase

struct ContentView: View {
    
    @State private var isUserCurrentlyLoggedOut: Bool = false
    
    var body: some View {
        NavigationView {
            if self.isUserCurrentlyLoggedOut {
                Home(isUserCurrentlyLoggedOut: $isUserCurrentlyLoggedOut)
            }else {
                LoginRegister(isUserCurrentlyLoggedOut: $isUserCurrentlyLoggedOut)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
LoginRegister.swift
 
//
//  LoginRegister.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI
import Firebase

struct LoginRegister: View {
    
    @State var isLoginMode = false
    @State var email = ""
    @State var password = ""
    @State var fname = ""
    @State var lname = ""
    
    @State private var shouldShowLoginAlert: Bool = false
    
    @State var StatusMessage = ""
    
    @Binding var isUserCurrentlyLoggedOut : Bool
    
    var body: some View {
        ScrollView {

            VStack(spacing: 16) {
                Picker(selection: $isLoginMode, label: Text("Picker here")) {
                    Text("Login")
                        .tag(true)
                    Text("Create Account")
                        .tag(false)
                }.pickerStyle(SegmentedPickerStyle())
                
                if !isLoginMode {
                    VStack {
                        Image(systemName: "person.fill")
                            .font(.system(size: 64))
                            .padding()
                            .foregroundColor(Color(.label))
                    }
                    .overlay(RoundedRectangle(cornerRadius: 64)
                                .stroke(Color.black, lineWidth: 3)
                    )
                    Group {
                        TextField("First Name", text: $fname)
                        TextField("Last Name", text: $lname)
                        TextField("Email", text: $email)
                            .keyboardType(.emailAddress)
                            .autocapitalization(.none)
                        SecureField("Password", text: $password)
                    }
                    .padding()
                    .background(Color.white)
                    .cornerRadius(10)
                    
                    Button {
                        handleAction()
                    } label: {
                        HStack {
                            Spacer()
                            Text("Create Account")
                                .foregroundColor(.white)
                                .padding(.vertical, 10)
                                .font(.system(size: 18, weight: .semibold))
                            Spacer()
                        }.background(Color.green)
  
                    }.cornerRadius(10)
                }else{
                    Image("Login")
                        .resizable()
                        .scaledToFill()
                        .frame(width: 128, height: 128)
                        .cornerRadius(64)
                    
                    Group {
                        TextField("Email", text: $email)
                            .keyboardType(.emailAddress)
                            .autocapitalization(.none)
                        SecureField("Password", text: $password)
                    }
                    .padding()
                    .background(Color.white)
                    .cornerRadius(10)
                    
                    Button {
                        loginUser()
                    } label: {
                        HStack {
                            Spacer()
                            Text("Login")
                                .foregroundColor(.white)
                                .padding(.vertical, 10)
                                .font(.system(size: 18, weight: .semibold))
                            Spacer()
                        }.background(Color.green)
  
                    }.cornerRadius(10)
                    .alert(isPresented: $shouldShowLoginAlert) {
                        Alert(title: Text("Email/Password incorrect"))
                    }
                }
                
                Text(self.StatusMessage)
                    .foregroundColor(Color.white)
                
            }.padding()
        } //End ScrollView
        .navigationViewStyle(StackNavigationViewStyle())
        .background(
            LinearGradient(gradient: Gradient(colors: [.white, .blue, .yellow]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)
        )
    }
    
    private func loginUser() {
        Auth.auth().signIn(withEmail: email, password: password) { result, err in
            if let err = err {
                print("Failed to login user:", err)
                self.StatusMessage = "Failed to login user: \(err)"
                self.shouldShowLoginAlert = true
                return
            }
  
            print("Successfully logged in as user: \(result?.user.uid ?? "")")
  
            self.StatusMessage = "Successfully logged in as user: \(result?.user.uid ?? "")"

            self.isUserCurrentlyLoggedOut = true
        }
    }
    
    private func handleAction() {
        createNewAccount()
    }
     
    private func createNewAccount() {
        Auth.auth().createUser(withEmail: email, password: password) { result, err in
            if let err = err {
                print("Failed to create user:", err)
                self.StatusMessage = "Failed to create user: \(err)"
                return
            }
            
            print("Successfully created user: \(result?.user.uid ?? "")")
  
            self.StatusMessage = "Successfully created user: \(result?.user.uid ?? "")"
            
            self.storeUserInformation()
        }
    }
    
    private func storeUserInformation() {
        guard let uid = Auth.auth().currentUser?.uid else { return }
        let userData = ["fname": self.fname, "lname": self.lname, "email": self.email, "profileImageUrl": "profileurl", "uid": uid]
        Firestore.firestore().collection("users")
            .document(uid).setData(userData) { err in
                if let err = err {
                    print(err)
                    self.StatusMessage = "\(err)"
                    return
                }
 
                print("Success")
            }
    }
}

struct LoginRegister_Previews: PreviewProvider {
    @State static var isUserCurrentlyLoggedOut = false
    static var previews: some View {
        LoginRegister(isUserCurrentlyLoggedOut: $isUserCurrentlyLoggedOut)
    }
}
Home.swift
 
//
//  Home.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI
import SDWebImageSwiftUI
import Firebase

struct Home: View {
    @State var shouldShowLogOutOptions = false
    
    @ObservedObject private var vm = MainMessagesViewModel()
    
    @Binding var isUserCurrentlyLoggedOut : Bool
    
    @State var index = 0
    
    var body: some View {
            
        VStack {
            //Text("User: \(vm.chatUser?.uid ?? "")")
            customNavBar

            ZStack {
                if self.index == 0 {
                    VStack {
                        Image("home")
                            .resizable()
                    }
                }
                else if self.index == 1 {
                    VStack {
                        Image("profile")
                            .resizable()
                    }
                }
                else if self.index == 2 {
                    Color.red.edgesIgnoringSafeArea(.top)
                    VStack {
                        Text("Notification").foregroundColor(Color.white)
                        Image(systemName: "bell.fill")
                            .resizable()
                            .frame(width: 200, height: 200)
                    }
                }
                else{
                    Color.yellow.edgesIgnoringSafeArea(.top)
                    VStack {
                        Text("Cart").foregroundColor(Color.white)
                        Image(systemName: "cart.fill")
                            .resizable()
                            .frame(width: 200, height: 200)
                    }
                }
            }
                 
            CustomTabBar(index: $index)
        }
        .navigationBarHidden(true)
        .animation(.spring())
    }
    
    private var customNavBar: some View {
        HStack(spacing: 16) {

            WebImage(url: URL(string: vm.chatUser?.profileImageUrl ?? ""))
                .resizable()
                .scaledToFill()
                .frame(width: 50, height: 50)
                .clipped()
                .cornerRadius(50)
                .overlay(RoundedRectangle(cornerRadius: 44)
                            .stroke(Color(.label), lineWidth: 1)
                )
                .shadow(radius: 5)
            
            VStack(alignment: .leading, spacing: 4) {
                let email = vm.chatUser?.email.replacingOccurrences(of: "@gmail.com", with: "") ?? ""
                Text(email)
                    .font(.system(size: 24, weight: .bold))
                
                HStack {
                    Circle()
                        .foregroundColor(.green)
                        .frame(width: 14, height: 14)
                    Text("online")
                        .font(.system(size: 12))
                        .foregroundColor(Color(.lightGray))
                }
                
            }
            
            Spacer()
            Button {
                shouldShowLogOutOptions.toggle()
            } label: {
                Image(systemName: "gear")
                    .font(.system(size: 24, weight: .bold))
                    .foregroundColor(Color(.label))
            }
        }
        .padding()
        .actionSheet(isPresented: $shouldShowLogOutOptions) {
            .init(title: Text("Settings"), message: Text("What do you want to do?"), buttons: [
                .destructive(Text("Sign Out"), action: {
                    print("handle sign out")
                    try? Auth.auth().signOut()
                    self.isUserCurrentlyLoggedOut = false
                }),
                    .cancel()
            ])
        }
    }
}

struct Home_Previews: PreviewProvider {
    @State static var isUserCurrentlyLoggedOut = false
    static var previews: some View {
        Home(isUserCurrentlyLoggedOut: $isUserCurrentlyLoggedOut)
    }
}
MainMessagesViewModel.swift
 
//
//  MainMessagesViewModel.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI
import SDWebImageSwiftUI
import Firebase

struct ChatUser {
    let uid, email, profileImageUrl: String
}

class MainMessagesViewModel: ObservableObject {
    
    @Published var errorMessage = ""
    @Published var chatUser: ChatUser?
    
    init() {
        
        fetchCurrentUser()
    }
    
    private func fetchCurrentUser() {

        guard let uid = Auth.auth().currentUser?.uid else {
            self.errorMessage = "Could not find firebase uid"
            return
        }
        
        
        Firestore.firestore().collection("users").document(uid).getDocument { snapshot, error in
            if let error = error {
                self.errorMessage = "Failed to fetch current user: \(error)"
                print("Failed to fetch current user:", error)
                return
            }
            
            self.errorMessage = "123"
            
            guard let data = snapshot?.data() else {
                self.errorMessage = "No data found"
                return
                
            }
            self.errorMessage = "Data: \(data.description)"
            let uid = data["uid"] as? String ?? ""
            let email = data["email"] as? String ?? ""
            let profileImageUrl = data["profileImageUrl"] as? String ?? ""
            
            self.chatUser = ChatUser(uid: uid, email: email, profileImageUrl: profileImageUrl)
            
            //self.errorMessage = chatUser.profileImageUrl
            
        }
    }
}
CustomTabBar.swift
 
//
//  CustomTabBar.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI
 
struct CustomTabBar : View {
     
    @Binding var index : Int
     
    var body: some View {
         
        HStack(spacing: 15) {
             
            HStack {
                Image(systemName: "house.fill")
                    .resizable()
                    .frame(width: 35, height: 30)
                 
                Text(self.index == 0 ? "Home" : "")
                    .fontWeight(.light)
                    .font(.system(size:14))
            }.padding(15)
            .background(self.index == 0 ? Color.green.opacity(0.5) : Color.clear)
            .clipShape(Capsule())
            .onTapGesture {
                self.index = 0
            }
             
            HStack {
                Image(systemName: "person.fill")
                    .resizable()
                    .frame(width: 35, height: 30)
                 
                Text(self.index == 1 ? "Profile" : "")
                    .fontWeight(.light)
                    .font(.system(size:14))
            }.padding(15)
            .background(self.index == 1 ? Color.blue.opacity(0.5) : Color.clear)
            .clipShape(Capsule())
            .onTapGesture {
                self.index = 1
            }
             
            HStack {
                Image(systemName: "bell.fill")
                    .resizable()
                    .frame(width: 35, height: 30)
                 
                Text(self.index == 2 ? "Notification" : "")
                    .fontWeight(.light)
                    .font(.system(size:14))
            }.padding(15)
            .background(self.index == 2 ? Color.red.opacity(0.5) : Color.clear)
            .clipShape(Capsule())
            .onTapGesture {
                self.index = 2
            }
             
            HStack {
                Image(systemName: "cart.fill")
                    .resizable()
                    .frame(width: 35, height: 30)
                 
                Text(self.index == 3 ? "Cart" : "")
                    .fontWeight(.light)
                    .font(.system(size:14))
            }.padding(15)
            .background(self.index == 3 ? Color.yellow.opacity(0.5) : Color.clear)
            .clipShape(Capsule())
            .onTapGesture {
                self.index = 3
            }
             
        }.padding(.top, 8)
        .frame(width: UIScreen.main.bounds.width)
        .background(Color.white)
        .animation(.default)
    }
}

struct CustomTabBar_Previews: PreviewProvider {
    @State static var index = 0
    static var previews: some View {
        CustomTabBar(index: $index)
    }
}
DevSwiftUIApp.swift
 
//
//  DevSwiftUIApp.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//
 
import SwiftUI
import Firebase
 
@main
struct DevSwiftUIApp: App {
     
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
      
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
  
class AppDelegate: NSObject,UIApplicationDelegate{
      
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
          
        FirebaseApp.configure()
        return true
    }
}

Tuesday, February 1, 2022

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

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

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

https://bootstrap-vue.org/

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

https://vuejs.org/v2/guide/

CREATE TABLE `vueuser` (
  `id` int(11) NOT NULL,
  `name` varchar(30) NOT NULL,
  `email` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `vueuser` (`id`, `name`, `email`) VALUES
(1, 'cairocoders', 'cairocoders@gmail.com'),
(2, 'tutorial101.blogspot.com', 'tutorial101@gmail.com'),
(3, 'Ashton Cox', 'AshtonCox@gmail.com'),
(4, 'Bradley Greer', 'BradleyGreer@gmail.com'),
(5, 'Clydey Ednalan', 'clydeyednalan@gmail.com');

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

ALTER TABLE `vueuser`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
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 href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<title>Vuejs PHP OOP PDO Mysql CRUD (Create, Read, Update and Delete)</title>
<style>
[v-cloak] {
    display: none;
}
</style>
</head>
<body class="bg-light">
    <div class="container" id="app" v-cloak>
        <div class="row">
            <div class="col-md-10"><h3>Vuejs PHP OOP PDO Mysql CRUD (Create, Read, Update and Delete)</h3>
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex d-flex justify-content-between">
                            <div class="lead">PHP PDO VUEJS CRUD</div>
                            <button id="show-btn" @click="showModal('my-modal')" class="btn btn-primary">Add Records</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="text-muted lead text-center" v-if="!records.length">No record found</div>
                        <div class="table table-success table-striped" v-if="records.length">
                            <table class="table table-borderless">
                                <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>
                                            <a href="#" @click.prevent="deleteRecord(record.id)" class="btn btn-danger">Delete</a>
                                            <a href="#" @click.prevent="editRecord(record.id)" class="btn btn-primary">Edit</a>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Add Records Modal -->
                <b-modal ref="my-modal" hide-footer title="Add Records">
					<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>
                    <b-button class="mt-3" variant="outline-danger" block @click="hideModal('my-modal')">Close Me</b-button>
                </b-modal>
						
                <!-- Update Record Modal -->
                <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>
<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 src="js/app.js"></script>
</body>
</html>
app.js
//app.js
var app = new Vue({
    el: "#app",
    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) => {
                        if (res.data.res == "success") {
                            app.makeToast("Success", "Record Added", "default");

                            this.name = "";
                            this.email = "";

                            app.hideModal("my-modal");
                            app.getRecords();
                        } else {
                            app.makeToast("Error", "Failed to add record. Please try again", "default");
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            } else {
                alert("All field are required");
            }
        },

        getRecords() {
            axios({
                url: "records.php",
                method: "get",
            })
                .then((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) => {
                        if (res.data.res == "success") {
                            app.makeToast("Success", "Record delete successfully", "default");
                            app.getRecords();
                        } else {
                            app.makeToast("Error", "Failed to delete record. Please try again", "default");
                        }
                    })
                    .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) => {
                        if (res.data.res == "success") {
                            app.makeToast("Sucess", "Record update successfully", "default");

                            this.edit_name = "";
                            this.edit_email = "";
                            this.edit_id = "";

                            app.hideModal("my-modal1");
                            app.getRecords();
                        }
                    })
                    .catch((err) => {
                        app.makeToast("Error", "Failed to update record", "default");
                    });
            } else {
                alert("All field are required");
            }
        },

        makeToast(vNodesTitle, vNodesMsg, variant) {
            this.$bvToast.toast([vNodesMsg], {
                title: [vNodesTitle],
                variant: variant,
                autoHideDelay: 1000,
                solid: true,
            });
        },
    },

    mounted: function () {
        this.getRecords();
    },
});
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 PDO("mysql:host=$this->server;dbname=$this->db", $this->username, $this->password);
		} catch (PDOException $e) {
			echo "Connection failed: " . $e->getMessage();
		}
	}

	public function store($name, $email)
	{
		$stmt = $this->conn->prepare("INSERT INTO `vueuser` (`name`, `email`) VALUES ('$name', '$email')");
		if ($stmt->execute()) {
			return true;
		} else {
			return;
		}
	}

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

		$stmt = $this->conn->prepare("SELECT * FROM `vueuser` ORDER BY `id` ASC");
		if ($stmt->execute()) {
			$data = $stmt->fetchAll();
		}

		return $data;
	}

	public function destroy($id)
	{
		$stmt = $this->conn->prepare("DELETE FROM `vueuser` WHERE `id` = '$id'");
		if ($stmt->execute()) {
			return true;
		} else {
			return;
		}
	}

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

		$stmt = $this->conn->prepare("SELECT * FROM `vueuser` WHERE `id` = '$id'");
		if ($stmt->execute()) {
			$data = $stmt->fetch();
		}

		return $data;
	}

	public function update($id, $name, $email)
	{
		$stmt = $this->conn->prepare("UPDATE `vueuser` SET `name` = '$name', `email` = '$email' WHERE `id` = '$id'");
		if ($stmt->execute()) {
			return true;
		} else {
			return;
		}
	}
}
records.php
//records.php
<?php 
	include 'model.php';

	$model = new Model();

	$rows = $model->findAll();

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

	echo json_encode($data);
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->store($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->findOne($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->destroy($id)) {
			$data = array('res' => 'success');
		}else{
			$data = array('res' => 'error');
		}

		echo json_encode($data);
	}

Monday, January 31, 2022

PHP Mysqli Datatables Server Side CRUD Ajax (Create, Read, Update and Delete)

PHP Mysqli Datatables Server Side CRUD Ajax (Create, Read, Update and Delete)

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

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.

https://datatables.net/

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `mobile` varchar(20) NOT NULL,
  `city` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `username`, `email`, `mobile`, `city`) VALUES
(7, 'Airi Satou', 'AiriSatou@gmail.com', '8887919632', 'Tokyo'),
(8, 'Angelica Ramos', 'AngelicaRamos@gmail.com', '8887919632', 'London'),
(9, 'Ashton Cox', 'AshtonCox@gmail.com', '8887919632', 'San Francisco'),
(10, 'Bradley Greer', 'BradleyGreer@gmail.com', '434334', 'London'),
(11, 'Brenden Wagner', 'BrendenWagner@gmail.com', '434334', 'San Francisco'),
(12, 'Brielle Williamson', 'BrielleWilliamson@gmail.com', '434334', 'New York'),
(13, 'Bruno Nash', 'BrunoNash@gmail.com', '9988999999', 'London'),
(15, 'Caesar Vance', 'CaesarVance@gmail.com', '8127956219', 'New York'),
(16, 'Cara Stevens', 'CaraStevens@gmail.com', '8127956219', 'New York'),
(18, 'Cedric Kelly', 'CedricKelly@gmail.com', '8127956219', 'Edinburgh'),
(19, 'Charde Marshall', 'ChardeMarshall@Gmail.com', '5464654654', 'San Francisco'),
(20, 'Colleen Hurst', 'ColleenHurst@Gmail.com', '5465465465', 'San Francisco'),
(21, 'Garrett Winters', 'GarrettWinters@gmail.com', '346546465', 'Olongapo City');

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

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
index.php
//index.php
<?php include('connection.php');?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.4/css/jquery.dataTables.min.css"/>
  <title>PHP Mysqli Datatables Server Side CRUD Ajax (Create, Read, Update and Delete)</title>
  <style type="text/css">
    .btnAdd {
      text-align: right;
      width: 83%;
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
<div class="container-fluid">
    <h2 class="text-center">PHP Mysqli Datatables Server Side CRUD Ajax (Create, Read, Update and Delete)</h2>
    <div class="row">
      <div class="container">
        <div class="btnAdd">
         <a href="#!" data-id="" data-bs-toggle="modal" data-bs-target="#addUserModal"   class="btn btn-success btn-sm" >Add User</a>
       </div>
       <div class="row">
        <div class="col-md-2"></div>
        <div class="col-md-8">
         <table id="example" class="table">
          <thead>
            <th>Id</th>
            <th>Name</th>
            <th>Email</th>
            <th>Mobile</th>
            <th>City</th>
            <th>Options</th>
          </thead>
          <tbody>
          </tbody>
        </table>
      </div>
      <div class="col-md-2"></div>
    </div>
  </div>
</div>
<?php include('modal.php'); ?>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      $('#example').DataTable({
        "fnCreatedRow": function( nRow, aData, iDataIndex ) {
          $(nRow).attr('id', aData[0]);
        },
        'serverSide':'true',
        'processing':'true',
        'paging':'true',
        'order':[],
        'ajax': {
          'url':'fetch_data.php',
          'type':'post',
        },
        "columnDefs": [{
          'target':[5],
          'orderable' :false,
        }]
      });
    } );
    $(document).on('submit','#addUser',function(e){
      e.preventDefault();
      var city= $('#addCityField').val();
      var username= $('#addUserField').val();
      var mobile= $('#addMobileField').val();
      var email= $('#addEmailField').val();
      if(city != '' && username != '' && mobile != '' && email != '' )
      {
       $.ajax({
         url:"add_user.php",
         type:"post",
         data:{city:city,username:username,mobile:mobile,email:email},
         success:function(data)
         {
           var json = JSON.parse(data);
           var status = json.status;
           if(status=='true')
           {
            mytable =$('#example').DataTable();
            mytable.draw();
            $('#addUserModal').modal('hide');
          }
          else
          {
            alert('failed');
          }
        }
      });
     }
     else {
      alert('Fill all the required fields');
    }
  });
    $(document).on('submit','#updateUser',function(e){
      e.preventDefault();
       var city= $('#cityField').val();
       var username= $('#nameField').val();
       var mobile= $('#mobileField').val();
       var email= $('#emailField').val();
       var trid= $('#trid').val();
       var id= $('#id').val();
       if(city != '' && username != '' && mobile != '' && email != '' )
       {
         $.ajax({
           url:"update_user.php",
           type:"post",
           data:{city:city,username:username,mobile:mobile,email:email,id:id},
           success:function(data)
           {
             var json = JSON.parse(data);
             var status = json.status;
             if(status=='true')
             {
              table =$('#example').DataTable();
              var button =   '<td><a href="javascript:void();" data-id="' +id + '" class="btn btn-info btn-sm editbtn">Edit</a>  <a href="#!"  data-id="' +id + '"  class="btn btn-danger btn-sm deleteBtn">Delete</a></td>';
              var row = table.row("[id='"+trid+"']");
              row.row("[id='" + trid + "']").data([id,username,email,mobile,city,button]);
              $('#exampleModal').modal('hide');
            }
            else
            {
              alert('failed');
            }
          }
        });
       }
       else {
        alert('Fill all the required fields');
      }
    });
    $('#example').on('click','.editbtn ',function(event){
      var table = $('#example').DataTable();
      var trid = $(this).closest('tr').attr('id');
     var id = $(this).data('id');
     $('#exampleModal').modal('show');

     $.ajax({
      url:"get_single_data.php",
      data:{id:id},
      type:'post',
      success:function(data)
      {
       var json = JSON.parse(data);
       $('#nameField').val(json.username);
       $('#emailField').val(json.email);
       $('#mobileField').val(json.mobile);
       $('#cityField').val(json.city);
       $('#id').val(id);
       $('#trid').val(trid);
     }
   })
   });

    $(document).on('click','.deleteBtn',function(event){
       var table = $('#example').DataTable();
      event.preventDefault();
      var id = $(this).data('id');
      if(confirm("Are you sure want to delete this User ? "))
      {
      $.ajax({
        url:"delete_user.php",
        data:{id:id},
        type:"post",
        success:function(data)
        {
          var json = JSON.parse(data);
          status = json.status;
          if(status=='success')
          {
             $("#"+id).closest('tr').remove();
          }
          else
          {
            alert('Failed');
            return;
          }
        }
      });
      }
      else
      {
        return null;
      }
    })
 </script>
</body>
</html>
modal.php
//modal.php
<!-- Add user Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add User</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="addUser" action="">
          <div class="mb-3 row">
            <label for="addUserField" class="col-md-3 form-label">Name</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="addUserField" name="name" >
            </div>
          </div>
          <div class="mb-3 row">
            <label for="addEmailField" class="col-md-3 form-label">Email</label>
            <div class="col-md-9">
              <input type="email" class="form-control" id="addEmailField" name="email">
            </div>
          </div>
          <div class="mb-3 row">
            <label for="addMobileField" class="col-md-3 form-label">Mobile</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="addMobileField" name="mobile">
            </div>
          </div>
          <div class="mb-3 row">
            <label for="addCityField" class="col-md-3 form-label">City</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="addCityField" name="City">
            </div>
          </div>
          <div class="text-center">
            <button type="submit" class="btn btn-primary">Submit</button>
          </div>
        </form> 
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
 <!-- Modal -->
 <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Update User</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="updateUser" >
          <input type="hidden" name="id" id="id" value="">
          <input type="hidden" name="trid" id="trid" value="">
          <div class="mb-3 row">
            <label for="nameField" class="col-md-3 form-label">Name</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="nameField" name="name" >
            </div>
          </div>
          <div class="mb-3 row">
            <label for="emailField" class="col-md-3 form-label">Email</label>
            <div class="col-md-9">
              <input type="email" class="form-control" id="emailField" name="email">
            </div>
          </div>
          <div class="mb-3 row">
            <label for="mobileField" class="col-md-3 form-label">Mobile</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="mobileField" name="mobile">
            </div>
          </div>
          <div class="mb-3 row">
            <label for="cityField" class="col-md-3 form-label">City</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="cityField" name="City">
            </div>
          </div>
          <div class="text-center">
            <button type="submit" class="btn btn-primary">Submit</button>
          </div>
        </form> 
      </div>
      <div class="modal-footer">
        <button type="button"  class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
connection.php
//connection.php
<?php
$con  = mysqli_connect('localhost','root','','testingdb');
if(mysqli_connect_errno())
{
    echo 'Database Connection Error';
}
fetch_data.php
//fetch_data.php
<?php include('connection.php');

$output= array();
$sql = "SELECT * FROM users ";

$totalQuery = mysqli_query($con,$sql);
$total_all_rows = mysqli_num_rows($totalQuery);

if(isset($_POST['search']['value']))
{
	$search_value = $_POST['search']['value'];
	$sql .= " WHERE username like '%".$search_value."%'";
	$sql .= " OR email like '%".$search_value."%'";
	$sql .= " OR mobile like '%".$search_value."%'";
	$sql .= " OR city like '%".$search_value."%'";
}

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

if($_POST['length'] != -1)
{
	$start = $_POST['start'];
	$length = $_POST['length'];
	$sql .= " LIMIT  ".$start.", ".$length;
}	

$query = mysqli_query($con,$sql);
$count_rows = mysqli_num_rows($query);
$data = array();
while($row = mysqli_fetch_assoc($query))
{
	$sub_array = array();
	$sub_array[] = $row['id'];
	$sub_array[] = $row['username'];
	$sub_array[] = $row['email'];
	$sub_array[] = $row['mobile'];
	$sub_array[] = $row['city'];
	$sub_array[] = '<a href="javascript:void();" data-id="'.$row['id'].'"  class="btn btn-info btn-sm editbtn" >Edit</a>  <a href="javascript:void();" data-id="'.$row['id'].'"  class="btn btn-danger btn-sm deleteBtn" >Delete</a>';
	$data[] = $sub_array;
}

$output = array(
	'draw'=> intval($_POST['draw']),
	'recordsTotal' =>$count_rows ,
	'recordsFiltered'=>   $total_all_rows,
	'data'=>$data,
);
echo  json_encode($output);
add_user.php
//add_user.php
<?php 
include('connection.php');
$username = $_POST['username'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$city = $_POST['city'];

$sql = "INSERT INTO `users` (`username`,`email`,`mobile`,`city`) values ('$username', '$email', '$mobile', '$city' )";
$query= mysqli_query($con,$sql);
$lastId = mysqli_insert_id($con);
if($query ==true)
{
    $data = array(
        'status'=>'true',
    );
    echo json_encode($data);
}
else
{
     $data = array(
        'status'=>'false',
    );
    echo json_encode($data);
} 
?>
get_single_data.php
//get_single_data.php
<?php include('connection.php');
$id = $_POST['id'];
$sql = "SELECT * FROM users WHERE id='$id' LIMIT 1";
$query = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($query);
echo json_encode($row);
?>
update_user.php
//update_user.php
<?php 
include('connection.php');
$username = $_POST['username'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$city = $_POST['city'];
$id = $_POST['id'];

$sql = "UPDATE `users` SET  `username`='$username' , `email`= '$email', `mobile`='$mobile',  `city`='$city' WHERE id='$id' ";
$query= mysqli_query($con,$sql);
$lastId = mysqli_insert_id($con);
if($query ==true)
{
   
    $data = array(
        'status'=>'true',
    );

    echo json_encode($data);
}
else
{
     $data = array(
        'status'=>'false',
    );
    echo json_encode($data);
} 
?>
delete_user.php
//delete_user.php
<?php 
include('connection.php');
$user_id = $_POST['id'];
$sql = "DELETE FROM users WHERE id='$user_id'";
$delQuery =mysqli_query($con,$sql);
if($delQuery==true)
{
	 $data = array(
        'status'=>'success',
    );
    echo json_encode($data);
}
else
{
     $data = array(
        'status'=>'failed',
    );
    echo json_encode($data);
} 
?>

Related Post