article

Wednesday, December 15, 2021

SwiftUI Firebase Register with Image Picker - Firebase Auth and Firebase Storage

SwiftUI Firebase Register with Image Picker - Firebase Auth and Firebase Storage

https://console.firebase.google.com/

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

import SwiftUI
import Firebase
import FirebaseStorage

struct ContentView: View {

    @State var email = ""
    @State var password = ""
    @State var StatusMessage = ""
    
    @State var shouldShowImagePicker = false
    @State var image: UIImage?
    
    var body: some View {
        NavigationView {
            ScrollView {

                VStack(spacing: 16) {
                    Text("Create Account")
                    
                    Button {
                        shouldShowImagePicker.toggle()
                    } label: {
                        VStack {
                            if let image = self.image {
                                Image(uiImage: image)
                                    .resizable()
                                    .scaledToFill()
                                    .frame(width: 128, height: 128)
                                    .cornerRadius(64)
                            } else {
                                Image(systemName: "person.fill")
                                    .font(.system(size: 64))
                                    .padding()
                                    .foregroundColor(Color(.label))
                            }
                        }
                        .overlay(RoundedRectangle(cornerRadius: 64)
                                    .stroke(Color.black, lineWidth: 3)
                        )
                    }

                    Group {
                        TextField("Email", text: $email)
                            .keyboardType(.emailAddress)
                            .autocapitalization(.none)
                        SecureField("Password", text: $password)
                    }
                    .padding(12)
                    .background(Color.white)
                    .cornerRadius(10)
                    
                    Button {
                        handleAction()
                    } label: {
                        HStack {
                            Spacer()
                            Text("Create Account")
                                .foregroundColor(.white)
                                .padding(.vertical, 10)
                                .font(.system(size: 14, weight: .semibold))
                            Spacer()
                        }.background(Color.blue)

                    }.cornerRadius(10)
                    
                    Text(self.StatusMessage)
                        
                }
                .padding()

            }
            .navigationViewStyle(StackNavigationViewStyle())
            .fullScreenCover(isPresented: $shouldShowImagePicker, onDismiss: nil) {
                ImagePicker(image: $image)
                    .ignoresSafeArea()
            }
            .background(
                        LinearGradient(gradient: Gradient(colors: [.orange, .gray]), startPoint: .top, endPoint: .bottom)
                            .edgesIgnoringSafeArea(.all))
        }
    }
    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.persistImageToStorage()
        }
    }
    
    private func persistImageToStorage() {
        guard let uid = Auth.auth().currentUser?.uid else { return }
        let ref = Storage.storage().reference(withPath: uid)
        guard let imageData = self.image?.jpegData(compressionQuality: 0.5) else { return }
        ref.putData(imageData, metadata: nil) { metadata, err in
            if let err = err {
                self.StatusMessage = "Failed to push image to Storage: \(err)"
                return
            }

            ref.downloadURL { url, err in
                if let err = err {
                    self.StatusMessage = "Failed to retrieve downloadURL: \(err)"
                    return
                }

                self.StatusMessage = "Successfully stored image with url: \(url?.absoluteString ?? "")"
                print(url?.absoluteString)
            }
        }
    }
}

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

import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {

    @Binding var image: UIImage?

    private let controller = UIImagePickerController()

    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }

    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

        let parent: ImagePicker

        init(parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            parent.image = info[.originalImage] as? UIImage
            picker.dismiss(animated: true)
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            picker.dismiss(animated: true)
        }

    }

    func makeUIViewController(context: Context) -> some UIViewController {
        controller.delegate = context.coordinator
        return controller
    }

    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {

    }

}
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
    }
}

SwiftUI Photo Library Image Picker

SwiftUI Photo Library Image Picker

ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var shouldShowImagePicker = false
    @State var image: UIImage?
    
    var body: some View {
        NavigationView {
            VStack {
                VStack {
                    ZStack(alignment: .top) {
                        Rectangle()
                            .foregroundColor(Color.green)
                            .edgesIgnoringSafeArea(.top)
                            .frame(height: 100)
                        
                        Button {
                            shouldShowImagePicker.toggle()
                        } label: {
                            VStack {
                                if let image = self.image {
                                    Image(uiImage: image)
                                        .resizable()
                                        .scaledToFill()
                                        .frame(width: 143, height: 143)
                                        .cornerRadius(80)
                                } else {
                                    Image(systemName: "person.fill")
                                        .font(.system(size: 80))
                                        .padding()
                                        .foregroundColor(Color(.label))
                                }
                            }
                            .overlay(RoundedRectangle(cornerRadius: 80)
                                        .stroke(Color.black, lineWidth: 3)
                            )
                        }
                    }//end Zstack
                }
                
                VStack(spacing: 15) {
                    VStack(spacing: 5) {
                        Text("Cairocoders")
                            .bold()
                            .font(.title)
                        Text("Coders")
                            .font(.body)
                            .foregroundColor(.secondary)
                    }.padding()
                    Text("SwiftUI Image Picker")
                        .multilineTextAlignment(.center)
                        .padding()
                    Spacer()
                }
                Spacer()
            }
        }
        .navigationViewStyle(StackNavigationViewStyle())
        .fullScreenCover(isPresented: $shouldShowImagePicker, onDismiss: nil) {
            ImagePicker(image: $image)
                .ignoresSafeArea()
        }
    }
}

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

struct ImagePicker: UIViewControllerRepresentable {

    @Binding var image: UIImage?

    private let controller = UIImagePickerController()

    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }

    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

        let parent: ImagePicker

        init(parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            parent.image = info[.originalImage] as? UIImage
            picker.dismiss(animated: true)
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            picker.dismiss(animated: true)
        }

    }

    func makeUIViewController(context: Context) -> some UIViewController {
        controller.delegate = context.coordinator
        return controller
    }

    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {

    }

}

SwiftUI Firebase Login Register - Firebase Auth

SwiftUI Firebase Login Register - Firebase Auth

https://console.firebase.google.com/

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

import SwiftUI
import Firebase

struct ContentView: View {

    @State var isLoginMode = false
    @State var email = ""
    @State var password = ""

    var body: some View {
        NavigationView {
            ScrollView {

                VStack(spacing: 16) {
                    Picker(selection: $isLoginMode, label: Text("Picker here")) {
                        Text("Login")
                            .tag(true)
                        Text("Create Account")
                            .tag(false)
                    }.pickerStyle(SegmentedPickerStyle())

                    if !isLoginMode {
                        Button {

                        } label: {
                            Image(systemName: "person.fill")
                                .font(.system(size: 64))
                                .padding()
                        }
                    }

                    Group {
                        TextField("Email", text: $email)
                            .keyboardType(.emailAddress)
                            .autocapitalization(.none)
                        SecureField("Password", text: $password)
                    }
                    .padding(12)
                    .background(Color.white)
                    .cornerRadius(10)
                    
                    Button {
                        handleAction()
                    } label: {
                        HStack {
                            Spacer()
                            Text(isLoginMode ? "Log In" : "Create Account")
                                .foregroundColor(.white)
                                .padding(.vertical, 10)
                                .font(.system(size: 14, weight: .semibold))
                            Spacer()
                        }.background(Color.blue)

                    }.cornerRadius(10)
                    
                    Text(self.loginStatusMessage)
                        
                }
                .padding()

            }
            .navigationTitle(isLoginMode ? "Log In" : "Create Account")
            .background(
                        LinearGradient(gradient: Gradient(colors: [.yellow, .green]), startPoint: .top, endPoint: .bottom)
                            .edgesIgnoringSafeArea(.all))
        }
    }
    private func handleAction() {
        if isLoginMode {
            loginUser()
        } else {
            createNewAccount()
        }
    }

    private func loginUser() {
        Auth.auth().signIn(withEmail: email, password: password) { result, err in
            if let err = err {
                print("Failed to login user:", err)
                self.loginStatusMessage = "Failed to login user: \(err)"
                return
            }

            print("Successfully logged in as user: \(result?.user.uid ?? "")")

            self.loginStatusMessage = "Successfully logged in as user: \(result?.user.uid ?? "")"
        }
    }

    @State var loginStatusMessage = ""

    private func createNewAccount() {
        Auth.auth().createUser(withEmail: email, password: password) { result, err in
            if let err = err {
                print("Failed to create user:", err)
                self.loginStatusMessage = "Failed to create user: \(err)"
                return
            }

            print("Successfully created user: \(result?.user.uid ?? "")")

            self.loginStatusMessage = "Successfully created user: \(result?.user.uid ?? "")"
        }
    }
    
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
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, December 14, 2021

AngularJS Form Validation with Bootstrap

AngularJS Form Validation with bootstrap

Angular Form Properties:

Property Name Description

$valid         This property tells that the form/input field value is valid. True/False.
$invalid         This property tells that the form/input field value is invalid. True/False.
$pristine         This boolean property tells that the form/input has not been used/modified yet.
$dirty         This boolean property tells that the form/input has been used/modified.
$touched         This boolean property says that input field is touched (applied only for input).
$untouched This boolean property says that input field is not touched yet (applied only for input).
$submitted This boolean property says that the form is submitted (applied only for form).


Classes:

Class Name Description

ng-valid         The input filed content is valid.
ng-invalid The input filed content is not valid.
ng-pristine The form/ input field has not been modified/used yet.
ng-dirty         The form/ input field has been modified/used.
ng-touched The input field has been touched.
ng-untouched The input field has not been touched yet.
//formvalidation.html
<!DOCTYPE html>
<html>
<head>
<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>
</head>
<body ng-app="validationApp" ng-controller="mainController">
<div class="container" style="width:600px">
    <div class="page-header"><h1>AngularJS Form Validation</h1></div>
    <form name="loginForm" ng-submit="submitForm(loginForm.$valid)" novalidate>
        <div class="form-group" ng-class="{ 'has-error' : loginForm.name.$invalid && !loginForm.name.$pristine }">
            <label>Name*</label>
            <input type="text" name="name" class="form-control" ng-model="name" ng-minlength="3" ng-maxlength="8" required>
            <p ng-show="loginForm.name.$dirty && loginForm.name.$error.required" class="help-block">Name is required</p>
            <p ng-show="loginForm.name.$error.minlength" class="help-block">Name is too short.</p>
            <p ng-show="loginForm.name.$error.maxlength" class="help-block">Name is too long.</p>
        </div>         
        <div class="form-group" ng-class="{ 'has-error' : loginForm.userName.$invalid && !loginForm.userName.$pristine }">
            <label>UserName(email)*</label>
            <input type="email" name="userName" class="form-control" ng-model="userName">
            <p ng-show="loginForm.userName.$invalid && !loginForm.userName.$pristine" class="help-block">Enter a valid email.</p>
        </div>
        <div class="form-group" ng-class="{ 'has-error' : loginForm.password.$invalid && !loginForm.password.$pristine }">
            <label>Password*</label>
            <input type="password" name="password" class="form-control" ng-model="password" ng-minlength="6" ng-maxlength="8" required>
            <p ng-show="loginForm.password.$invalid && !loginForm.password.$pristine" class="help-block">Password must be between 6-8 characters.</p>
        </div>        
        <button type="submit" class="btn btn-primary" ng-disabled="loginForm.$invalid">Submit</button>        
    </form>
    </div>
<script>
var validationApp = angular.module('validationApp', []);

validationApp.controller('mainController', function($scope) {

	// function to submit the form after all validation has occurred			
	$scope.submitForm = function(isValid) {

		// check to make sure the form is completely valid
		if (isValid) { 
			alert('Login Form is valid');
		}
	};
});
</script>
</body>
</html>

AngularJS Live Data Search with PHP Mysql and bootstrap

AngularJS Live Data Search with PHP Mysql and bootstrap

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 href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
</head>
<body>
<div class="container" ng-app="angularlivesearch" ng-controller="search_controller" ng-init="fetchData()">
	<br />
	<h3 align="center">AngularJS Live Data Search with PHP Mysql and bootstrap</h3>
	<br />
	<div class="form-group">
		<div class="input-group">
		 <span class="input-group-addon">Search</span>
		 <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}
		}).success(function(data){
			$scope.searchData = 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);
}

?>

Friday, December 10, 2021

SwiftUI Searchable

SwiftUI Searchable

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

import SwiftUI

struct ContentView: View {

    @State var search = ""
    
    var body: some View {
        NavigationView {
            List {
                ForEach(datarecipe.filter{(self.search.isEmpty ? true : $0.name.localizedCaseInsensitiveContains(self.search))}, id: \.id) { info in
                    Text(info.name)
                        .font(.title)
                        .fontWeight(.bold)
                    
                    Image(info.image)
                        .renderingMode(.original)
                        .resizable()
                        .frame(height: 200)
                        .cornerRadius(10)
                }
            }.navigationTitle("Searchable")
                .searchable(text: self.$search)
            {
                ForEach(datarecipe, id:\.id) { info in
                    HStack {
                        Text(info.name)
                            .searchCompletion(info.name)
                    }
                }
            }
        }
    }
}

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

import Foundation
 
struct Recipe : Identifiable {
     
    var id : Int
    var name : String
    var image : String
}
 
var datarecipe = [
 
    Recipe(id: 0, name: "Bistek Tagalog", image: "1"),
    Recipe(id: 1, name: "Boogie flight", image: "2"),
    Recipe(id: 2, name: "Sinigang Na Baboy", image: "3"),
    Recipe(id: 3, name: "Ginisang Togue", image: "4"),
    Recipe(id: 4, name: "Ginisang Munggo (Monggo)", image: "5"),
    Recipe(id: 5, name: "Pork Estofado (Sweet Pork Stew)", image: "6"),
    Recipe(id: 6, name: "Pata Tim", image: "7"),
    Recipe(id: 7, name: "Pancit Palabok", image: "8"),
]

Thursday, December 9, 2021

PHP MYSQL PDO Todo List with JQuery AJAX

PHP MYSQL PDO Todo List with JQuery AJAX

CREATE TABLE `todos` (
  `id` int(11) NOT NULL,
  `title` text NOT NULL,
  `date_time` datetime NOT NULL DEFAULT current_timestamp(),
  `checked` tinyint(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

ALTER TABLE `todos`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
index.php
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>PHP MYSQL PDO Todo List with JQuery AJAX</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">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php require 'dbconn.php'; ?>
    <div class="container"><h1>PHP MYSQL PDO Todo List with JQuery AJAX</h1>
        <div class="row">
			<div class="col-2"></div>
			<div class="col-9" style="border-radius: 5px;background-color:#fff;padding:30px;">
			 <form action="add.php" method="POST" autocomplete="off">
				 <?php if(isset($_GET['mess']) && $_GET['mess'] == 'error'){ ?>
					<p><input type="text" name="title" class="form-control form-control-lg" placeholder="This field is required" /></p>
					<p><button type="submit" class="btn btn-primary btn-lg">Add   <span>+</span></button></p>

				 <?php }else{ ?>
				  <p><input type="text" name="title" class="form-control form-control-lg" placeholder="What do you need to do?" /></p>
				  <p><button type="submit" class="btn btn-primary btn-lg">Add   <span>+</span></button></p>
				 <?php } ?>
			</form>
			</div>
			<div class="col-2"></div>
       </div>
       <?php 
          $todos = $conn->query("SELECT * FROM todos ORDER BY id DESC");
       ?>
       <div class="row">
			<div class="col-2"></div>
			<div class="col-9" style="border-radius: 5px;background-color:#fff;padding:30px;margin-top:20px;">
            <?php if($todos->rowCount() <= 0){ ?>
                <div class="todo-item">
                    <div class="empty">
                        <h1>No Record </h1>
                    </div>
                </div>
            <?php } ?>

            <?php while($todo = $todos->fetch(PDO::FETCH_ASSOC)) { ?>
                <div class="todo-item">
                    <span id="<?php echo $todo['id']; ?>" class="remove-to-do">x</span>
                    <?php if($todo['checked']){ ?> 
                        <input type="checkbox" class="check-box" data-todo-id ="<?php echo $todo['id']; ?>" checked />
                        <h2 class="checked"><?php echo $todo['title'] ?></h2>
                    <?php }else { ?>
                        <input type="checkbox" data-todo-id ="<?php echo $todo['id']; ?>" class="check-box" />
                        <h2><?php echo $todo['title'] ?></h2>
                    <?php } ?>
                    <br>
                    <small>created: <?php echo $todo['date_time'] ?></small> 
                </div>
            <?php } ?>
			</div>
			<div class="col-2"></div>
       </div>
    </div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous"></script>
<!-- https://code.jquery.com/ -->
<script>
        $(document).ready(function(){
            $('.remove-to-do').click(function(){
                const id = $(this).attr('id');
                
                $.post("remove.php", 
                      {
                          id: id
                      },
                      (data)  => {
                         if(data){
                             $(this).parent().hide(600);
                         }
                      }
                );
            });

            $(".check-box").click(function(e){
                const id = $(this).attr('data-todo-id');
                
                $.post('check.php', 
                      {
                          id: id
                      },
                      (data) => {
                          if(data != 'error'){
                              const h2 = $(this).next();
                              if(data === '1'){
                                  h2.removeClass('checked');
                              }else {
                                  h2.addClass('checked');
                              }
                          }
                      }
                );
            });
        });
</script>
</body>
</html>
dbconn.php
//dbconn.php
<?php 
$sName = "localhost";
$uName = "root";
$pass = "";
$db_name = "testingdb";

try {
    $conn = new PDO("mysql:host=$sName;dbname=$db_name", 
                    $uName, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
  echo "Connection failed : ". $e->getMessage();
}
add.php
//add.php
<?php
if(isset($_POST['title'])){
    require 'dbconn.php';

    $title = $_POST['title'];

    if(empty($title)){
        header("Location: index.php?mess=error");
    }else {
        $stmt = $conn->prepare("INSERT INTO todos(title) VALUE(?)");
        $res = $stmt->execute([$title]);

        if($res){
            header("Location: index.php?mess=success"); 
        }else {
            header("Location: index.php");
        }
        $conn = null;
        exit();
    }
}else {
    header("Location: index.php?mess=error");
}
check.php
//check.php
<?php
if(isset($_POST['id'])){
    require 'dbconn.php';

    $id = $_POST['id'];

    if(empty($id)){
       echo 'error';
    }else {
        $todos = $conn->prepare("SELECT id, checked FROM todos WHERE id=?");
        $todos->execute([$id]);

        $todo = $todos->fetch();
        $uId = $todo['id'];
        $checked = $todo['checked'];

        $uChecked = $checked ? 0 : 1;

        $res = $conn->query("UPDATE todos SET checked=$uChecked WHERE id=$uId");

        if($res){
            echo $checked;
        }else {
            echo "error";
        }
        $conn = null;
        exit();
    }
}else {
    header("Location: index.php?mess=error");
}
remove.php
//remove.php
<?php
if(isset($_POST['id'])){
    require 'dbconn.php';

    $id = $_POST['id'];

    if(empty($id)){
       echo 0;
    }else {
        $stmt = $conn->prepare("DELETE FROM todos WHERE id=?");
        $res = $stmt->execute([$id]);

        if($res){
            echo 1;
        }else {
            echo 0;
        }
        $conn = null;
        exit();
    }
}else {
    header("Location: index.php?mess=error");
}
css/style.css
//css/style.css
body {
    background: #6d5ce8;
  }
  
  * {
    padding: 0px;
    margin: 0px;
    box-sizing: border-box;
  }
  
  .todo-item {
    width: 95%;
    margin: 10px auto;
    padding: 20px 10px;
    box-shadow: 0 4px 8px 0 #ccc, 0 6px 20px 0 #ccc;
    border-radius: 5px;
  }
  
  .todo-item h2 {
    display: inline-block;
    padding: 5px 0px;
    font-size: 17px;
    font-family: sans-serif;
    color: #555;
  }
  
  .todo-item small {
    display: block;
    width: 100%;
    padding: 5px 0px;
    color: #888;
    padding-left: 30px;
    font-size: 14px;
    font-family: sans-serif; 
  }
  
  .remove-to-do {
    display: block;
    float: right;font-size:20px;
    width: 35px;
    height: 35px;
    color: rgb(139, 97, 93);
    text-decoration: none;
    padding: 0px 5px 8px 10px;
    border-radius: 50%;
    transition: background 1s;
    cursor: pointer;
  }
  
  .remove-to-do:hover {
    background: rgb(139, 97, 93);
    color: #fff;
  }
  
  .checked {
    color: #999 !important;
    text-decoration: line-through;
  }
  
  .todo-item input {
    margin: 0px 5px;
  }
  
  .empty {
    font-family: sans-serif;
    font-size: 16px;
    text-align: center;
    color: #cccc;
  }

PHP Mysql PDO CRUD(Create, Read, Update and Delete) Search and Pagination with jQuery Ajax Bootstrap

PHP Mysql PDO CRUD(Create, Read, Update and Delete) Search and Pagination with jQuery Ajax Bootstrap

PHP Class Mysql PDO CRUD(Create, Read, Update and Delete) with Search Functionality and Ajax Pagination

Bootstrap https://getbootstrap.com/docs/4.5/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css

Modal
https://getbootstrap.com/docs/4.5/components/modal/
https://getbootstrap.com/docs/4.5/components/spinners/#size

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,
  `photo` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

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

ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25;

index.php
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PHP Mysql PDO CRUD(Create, Read, Update and Delete) Search and Pagination with jQuery Ajax Bootstrap</title>
  <link rel="stylesheet" href="css/style.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
</head>
<body>
<div class="container">
    <div class="row text-center"> 
      <h2>PHP Mysql PDO CRUD(Create, Read, Update and Delete) Search and Pagination with jQuery Ajax Bootstrap</h2>
    </div>
    <div class="alert alert-success text-center message" role="alert"></div>
    
	<div class="row mb-3">
      <div class="col-3">
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#employeeModal" id="addnewbtn">Add New </button>
      </div>
      <div class="col-9">
        <div class="input-group input-group-lg">
          <div class="input-group-prepend">
            <span class="input-group-text" id="basic-addon2"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-search" viewBox="0 0 16 16">
  <path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
</svg></span>
          </div>
          <input type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-lg" placeholder="Search..." id="searchinput">

        </div>
      </div>
    </div>
	
	<table class="table" id="employeetable">
	  <thead>
		<tr>
		  <th scope="col"></th>
		  <th scope="col">Name</th>
		  <th scope="col">Position</th>
		  <th scope="col">Office</th>
		  <th scope="col">Age</th>
		  <th scope="col">Salary</th>
		  <th scope="col"></th>
		</tr>
	  </thead>
	  <tbody>
	  </tbody>
	</table>

    <nav id="pagination"></nav>
    <input type="hidden" name="currentpage" id="currentpage" value="1">
<?php
//modal
include_once 'formModal.php';
include_once 'viewModal.php';
?>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script src="js/script.js"></script>
<div id="overlay" style="display:none;">
    <div class="spinner-border text-danger" style="width: 3rem; height: 3rem;"></div>
    <br />
    Loading...
</div> 
</body>
</html>
formModal.php
//formModal.php
<!-- add/edit form modal -->
<div class="modal fade" id="employeeModal" tabindex="-1" role="dialog" aria-labelledby="employeeModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add/Edit Employee</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <form id="addform" method="POST" enctype="multipart/form-data">
        <div class="modal-body">
          <div class="form-group">
            <label for="recipient-name" class="col-form-label">Name:</label>
            <div class="input-group mb-3">
              <input type="text" class="form-control" id="name" name="name" required="required">
            </div>
          </div>
          <div class="form-group">
            <label for="message-text" class="col-form-label">Position:</label>
            <div class="input-group mb-3">
              <input type="text" class="form-control" id="position" name="position" required="required">
            </div>
          </div>
          <div class="form-group">
            <label for="message-text" class="col-form-label">Office:</label>
            <div class="input-group mb-3">
              <input type="text" class="form-control" id="office" name="office" required="required">
            </div>
          </div>
          <div class="form-group">
            <label for="message-text" class="col-form-label">Photo:</label>
            <div class="input-group mb-3">
              <div class="custom-file">
                <input type="file" class="custom-file-input" name="photo" id="userphoto">
                <label class="custom-file-label" for="userphoto">Choose file</label>
              </div>
            </div>
          </div>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-success" id="addButton">Submit</button>
          <input type="hidden" name="action" value="addnew">
          <input type="hidden" name="employeeid" id="employeeid" value="">
        </div>
      </form>
    </div>
  </div>
</div>
<!-- add/edit form modal end -->
viewModal.php
//viewModal.php
<!-- profile modal start -->
<div class="modal fade" id="empViewModal" tabindex="-1" role="dialog" aria-labelledby="empViewModalLabel"
  aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Profile <i class="fa fa-user-circle-o"
            aria-hidden="true"></i></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="container" id="profile"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
      </form>
    </div>
  </div>
</div>
<!-- profile modal end -->
js/script.js
//js/script.js
// get pagination
function pagination(totalpages, currentpage) {
  var pagelist = "";
  if (totalpages > 1) {
    currentpage = parseInt(currentpage);
    pagelist += `<ul class="pagination justify-content-center">`;
    const prevClass = currentpage == 1 ? " disabled" : "";
    pagelist += `<li class="page-item${prevClass}"><a class="page-link" href="#" data-page="${
      currentpage - 1
    }">Previous</a></li>`;
    for (let p = 1; p <= totalpages; p++) {
      const activeClass = currentpage == p ? " active" : "";
      pagelist += `<li class="page-item${activeClass}"><a class="page-link" href="#" data-page="${p}">${p}</a></li>`;
    }
    const nextClass = currentpage == totalpages ? " disabled" : "";
    pagelist += `<li class="page-item${nextClass}"><a class="page-link" href="#" data-page="${
      currentpage + 1
    }">Next</a></li>`;
    pagelist += `</ul>`;
  }

  $("#pagination").html(pagelist);
}

// get employee row
function getemployeerow(employee) {
  var employeeRow = "";
  if (employee) {
    const userphoto = employee.photo ? employee.photo : "default.png";
    employeeRow = `<tr>
          <td class="align-middle"><img src="uploads/${userphoto}" height="50" class="img-thumbnail rounded float-left"></td>
          <td class="align-middle">${employee.name}</td>
          <td class="align-middle">${employee.position}</td>
          <td class="align-middle">${employee.office}</td>
          <td class="align-middle">${employee.age}</td>
          <td class="align-middle">${employee.salary}</td>
          <td class="align-middle">
            <a href="#" class="btn btn-success mr-3 profile" data-toggle="modal" data-target="#empViewModal"
              title="Prfile" data-id="${employee.id}">View</a>
            <a href="#" class="btn btn-warning mr-3 editemployee" data-toggle="modal" data-target="#employeeModal"
              title="Edit" data-id="${employee.id}">Edit</a>
            <a href="#" class="btn btn-danger deletetemployee" data-id="${employee.id}" title="Delete" data-id="${employee.id}">Delete</a>
          </td>
        </tr>`;
  }
  return employeeRow;
}

// get employees list
function listemployee() {
  var pageno = $("#currentpage").val();
  $.ajax({
    url: "/devtest/phpcrudajax/ajax.php",
    type: "GET",
    dataType: "json",
    data: { page: pageno, action: "getusers" },
    beforeSend: function () {
      $("#overlay").fadeIn();
    },
    success: function (rows) {
      console.log(rows);  
      if (rows.jsonemplyee) { 
        var employeeslist = "";
        $.each(rows.jsonemplyee, function (index, employee) {
          employeeslist += getemployeerow(employee);
        });
        $("#employeetable tbody").html(employeeslist);
        let totalemployees = rows.count;
        let totalpages = Math.ceil(parseInt(totalemployees) / 4);
        const currentpage = $("#currentpage").val();
        pagination(totalpages, currentpage);
        $("#overlay").fadeOut();
      }
    },
    error: function () {
      console.log("something went wrong");
    },
  });
}


$(document).ready(function () {
	
  // pagination
  $(document).on("click", "ul.pagination li a", function (e) {
    e.preventDefault();
    var $this = $(this);
    const pagenum = $this.data("page");
    $("#currentpage").val(pagenum);
    listemployee();
    $this.parent().siblings().removeClass("active");
    $this.parent().addClass("active");
  });
  // form reset on new button
  $("#addnewbtn").on("click", function () {
    $("#addform")[0].reset();
    $("#employeeid").val("");
  });
  
    // searching
  $("#searchinput").on("keyup", function () {
    const searchText = $(this).val();
    if (searchText.length > 1) {
      $.ajax({
        url: "/devtest/phpcrudajax/ajax.php",
        type: "GET",
        dataType: "json",
        data: { searchQuery: searchText, action: "search" },
        success: function (employees) {
          if (employees) {
            var employeeslist = "";
            $.each(employees, function (index, employee) {
              employeeslist += getemployeerow(employee);
            });
            $("#employeetable tbody").html(employeeslist);
            $("#pagination").hide();
          }
        },
        error: function () {
          console.log("something went wrong");
        },
      });
    } else {
      listemployee();
      $("#pagination").show();
    }
  });
  
  // add/edit user
  $(document).on("submit", "#addform", function (event) {
    event.preventDefault();
    var alertmsg =
      $("#employeeid").val().length > 0
        ? "Employee has been updated Successfully!"
        : "New employee has been added Successfully!";
    $.ajax({
      url: "/devtest/phpcrudajax/ajax.php",
      type: "POST",
      dataType: "json",
      data: new FormData(this),
      processData: false,
      contentType: false,
      beforeSend: function () {
        $("#overlay").fadeIn();
      },
      success: function (response) {
        console.log(response);
        if (response) {
          $("#employeeModal").modal("hide");
          $("#addform")[0].reset();
          $(".message").html(alertmsg).fadeIn().delay(3000).fadeOut();
          listemployee();
          $("#overlay").fadeOut();
        }
      },
      error: function () {
        console.log("Oops! Something went wrong!");
      },
    });
  });
  
  //get user
  $(document).on("click", "a.editemployee", function () {
    var empid = $(this).data("id");

    $.ajax({
      url: "/devtest/phpcrudajax/ajax.php",
      type: "GET",
      dataType: "json",
      data: { id: empid, action: "getuser" },
      beforeSend: function () {
        $("#overlay").fadeIn();
      },
      success: function (employee) {
        if (employee) {
          $("#name").val(employee.name);
          $("#position").val(employee.position);
          $("#office").val(employee.office);
          $("#employeeid").val(employee.id);
        }
        $("#overlay").fadeOut();
      },
      error: function () {
        console.log("something went wrong");
      },
    });
  });
  
  // get profile
  $(document).on("click", "a.profile", function () {
    var pid = $(this).data("id");
    $.ajax({
      url: "/devtest/phpcrudajax/ajax.php",
      type: "GET",
      dataType: "json",
      data: { id: pid, action: "getuser" },
      success: function (employee) {
        if (employee) {
          const userphoto = employee.photo ? employee.photo : "default.png";
          const profile = `<div class="row">
                <div class="col-sm-6 col-md-4">
                  <img src="uploads/${userphoto}" class="rounded responsive" />
                </div>
                <div class="col-sm-6 col-md-8">
                  <h4 class="text-primary">${employee.name}</h4>
                  <p class="text-secondary">
                    Position : ${employee.position}
                    <br />
                    Office : ${employee.office}
                  </p>
                </div>
              </div>`;
          $("#profile").html(profile);
        }
      },
      error: function () {
        console.log("something went wrong");
      },
    });
  });
  
  // delete user
  $(document).on("click", "a.deletetemployee", function (e) {
    e.preventDefault();
    var pid = $(this).data("id");
    if (confirm("Are you sure want to delete this?")) {
      $.ajax({
        url: "/devtest/phpcrudajax/ajax.php",
        type: "GET",
        dataType: "json",
        data: { id: pid, action: "deletetemployee" },
        beforeSend: function () {
          $("#overlay").fadeIn();
        },
        success: function (res) {
          if (res.deleted == 1) {
            $(".message")
              .html("employee has been deleted successfully!")
              .fadeIn()
              .delay(3000)
              .fadeOut();
            listemployee();
            $("#overlay").fadeOut();
          }
        },
        error: function () {
          console.log("something went wrong");
        },
      });
    }
  });
  
  // load employees
  listemployee();
});
ajax.php
//ajax.php
<?php
$action = $_REQUEST['action'];

if (!empty($action)) {
    require_once 'Employee.php';
    $obj = new Employee();
}

if ($action == 'addnew' && !empty($_POST)) {
    $name = $_POST['name'];
    $position = $_POST['position'];
    $office = $_POST['office'];
    $photo = $_FILES['photo'];
    $employeeID = (!empty($_POST['employeeid'])) ? $_POST['employeeid'] : '';

    // file (photo) upload
    $imagename = '';
    if (!empty($photo['name'])) {
        $imagename = $obj->uploadPhoto($photo);
        $employeeData = [
            'name' => $name,
            'position' => $position,
            'office' => $office,
            'photo' => $imagename,
        ];
    } else {
        $employeeData = [
            'name' => $name,
            'position' => $position,
            'office' => $office,
        ];
    }

    if ($employeeID) {
        $obj->update($employeeData, $employeeID);
    } else {
        $employeeID = $obj->add($employeeData);
    }

    if (!empty($employeeID)) {
        $employeejson = $obj->getRow('id', $employeeID);
        echo json_encode($employeejson);
        exit();
    }
}

if ($action == "getusers") {
    $page = (!empty($_GET['page'])) ? $_GET['page'] : 1;
    $limit = 4;
    $start = ($page - 1) * $limit;

    $employee = $obj->getRows($start, $limit);
    if (!empty($employee)) {
        $employeelist = $employee;
    } else {
        $employeelist = [];
    }
    $total = $obj->getCount();
    $empjson = ['count' => $total, 'jsonemplyee' => $employeelist];
    echo json_encode($empjson);
    exit();
}

if ($action == "getuser") {
    $employeeID = (!empty($_GET['id'])) ? $_GET['id'] : '';
    if (!empty($employeeID)) {
        $employeejsongetuser = $obj->getRow('id', $employeeID);
        echo json_encode($employeejsongetuser);
        exit();
    }
}

if ($action == "deletetemployee") {
    $employeeID = (!empty($_GET['id'])) ? $_GET['id'] : '';
    if (!empty($employeeID)) {
        $isDeleted = $obj->deleteRow($employeeID);
        if ($isDeleted) {
            $message = ['deleted' => 1];
        } else {
            $message = ['deleted' => 0];
        }
        echo json_encode($message);
        exit();
    }
}

if ($action == 'search') {
    $queryString = (!empty($_GET['searchQuery'])) ? trim($_GET['searchQuery']) : '';
    $results = $obj->searchEmployee($queryString);
    echo json_encode($results);
    exit();
}
Db.php
//Db.php
<?php
class Database
{
    private $dbServer = 'localhost';
    private $dbUser = 'root';
    private $dbPassword = '';
    private $dbName = 'testingdb';
    protected $conn;

    public function __construct()
    {
        try {
            $dsn = "mysql:host={$this->dbServer}; dbname={$this->dbName}; charset=utf8";
            $options = array(PDO::ATTR_PERSISTENT);
            $this->conn = new PDO($dsn, $this->dbUser, $this->dbPassword, $options);
        } catch (PDOException $e) {
            echo "Connection Error: " . $e->getMessage();
        }

    }
}
Employee.php
//Employee.php
<?php
require_once 'Db.php';

class Employee extends Database
{
    // table name
    protected $tableName = 'employee';

    //function is used to add record
    public function add($data)
    {
        if (!empty($data)) {
            $fileds = $placholders = [];
            foreach ($data as $field => $value) {
                $fileds[] = $field;
                $placholders[] = ":{$field}";
            }
        }

        $sql = "INSERT INTO {$this->tableName} (" . implode(',', $fileds) . ") VALUES (" . implode(',', $placholders) . ")";
        $stmt = $this->conn->prepare($sql);
        try {
            $this->conn->beginTransaction();
            $stmt->execute($data);
            $lastInsertedId = $this->conn->lastInsertId();
            $this->conn->commit();
            return $lastInsertedId;
        } catch (PDOException $e) {
            echo "Error: " . $e->getMessage();
            $this->conn->rollback();
        }

    }

	//function update record
    public function update($data, $id)
    {
        if (!empty($data)) {
            $fileds = '';
            $x = 1;
            $filedsCount = count($data);
            foreach ($data as $field => $value) {
                $fileds .= "{$field}=:{$field}";
                if ($x < $filedsCount) {
                    $fileds .= ", ";
                }
                $x++;
            }
        }
        $sql = "UPDATE {$this->tableName} SET {$fileds} WHERE id=:id";
        $stmt = $this->conn->prepare($sql);
        try {
            $this->conn->beginTransaction();
            $data['id'] = $id;
            $stmt->execute($data);
            $this->conn->commit();
        } catch (PDOException $e) {
            echo "Error: " . $e->getMessage();
            $this->conn->rollback();
        }

    }

    //function to get records

    public function getRows($start = 0, $limit = 4)
    {
        $sql = "SELECT * FROM {$this->tableName} ORDER BY id DESC LIMIT {$start},{$limit}";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {

            $results = [];
        }
        return $results;
    }

    // delete row using id
    public function deleteRow($id)
    {
        $sql = "DELETE FROM {$this->tableName}  WHERE id=:id";
        $stmt = $this->conn->prepare($sql);
        try {
            $stmt->execute([':id' => $id]);
            if ($stmt->rowCount() > 0) {
                return true;
            }
        } catch (PDOException $e) {
            echo "Error: " . $e->getMessage();
            return false;
        }

    }

    public function getCount()
    {
        $sql = "SELECT count(*) as pcount FROM {$this->tableName}";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result['pcount'];
    }
	
    //function to get single record based on the column value
    public function getRow($field, $value)
    {

        $sql = "SELECT * FROM {$this->tableName}  WHERE {$field}=:{$field}";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute([":{$field}" => $value]);
        if ($stmt->rowCount() > 0) {
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
        } else {
            $result = [];
        }

        return $result;
    }

	//function for search table fields name
    public function searchEmployee($searchText, $start = 0, $limit = 4)
    {
        $sql = "SELECT * FROM {$this->tableName} WHERE name LIKE :search ORDER BY id DESC LIMIT {$start},{$limit}";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute([':search' => "{$searchText}%"]);
        if ($stmt->rowCount() > 0) {
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            $results = [];
        }

        return $results;
    }
	
    //funciton to upload file
    public function uploadPhoto($file)
    {
        if (!empty($file)) {
            $fileTempPath = $file['tmp_name'];
            $fileName = $file['name'];
            $fileSize = $file['size'];
            $fileType = $file['type'];
            $fileNameCmps = explode('.', $fileName);
            $fileExtension = strtolower(end($fileNameCmps));
            $newFileName = md5(time() . $fileName) . '.' . $fileExtension;
            $allowedExtn = ["jpg", "png", "gif", "jpeg"];
            if (in_array($fileExtension, $allowedExtn)) {
                $uploadFileDir = getcwd() . '/uploads/';
                $destFilePath = $uploadFileDir . $newFileName;
                if (move_uploaded_file($fileTempPath, $destFilePath)) {
                    return $newFileName;
                }
            }

        }
    }
} //End Class Employee
css/style.css
//css/style.css
.container {
  padding-top: 10px;
}
.rounded {
  width: 100px;
}
.img-thumbnail {
  width: 80px !important;
}
.message {
  display: none;
}
#overlay {
  background: #ffffff;
  color: #666666;
  position: fixed;
  height: 100%;
  width: 100%;
  z-index: 5000;
  top: 0;
  left: 0;
  float: left;
  text-align: center;
  padding-top: 25%;
  opacity: 0.8;
}

Tuesday, December 7, 2021

AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi

AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi

https://angularjs.org/

HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. AngularJS lets you extend HTML vocabulary for your application. 

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

AngularUI Router https://github.com/angular-ui/ui-router

Angular UI-Router is a client-side Single Page Application routing framework for AngularJS. Routing frameworks for SPAs update the browser's URL as the user navigates through the app.

CDN Minified : http://unpkg.com/@uirouter/angularjs@latest/release/angular-ui-router.min.js

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');

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;


index.html
//index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="https://unpkg.com/@uirouter/angularjs@1.0.30/release/angular-ui-router.min.js"></script>
</head>
<body ng-app="appcrudrouter">
<nav class="navbar navbar-inverse" role="navigation">
    <div class="navbar-header">
        <a class="navbar-brand" ui-sref="#">AngularUI Router</a>
    </div>
    <ul class="nav navbar-nav">
        <li><a ui-sref="home">Home</a></li>
        <li><a ui-sref="about">About</a></li>
        <li><a ui-sref="contact">Contact</a></li>
    </ul>
</nav>
<div class="container">
    <h1 class="page-header text-center">AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi</h1>
    <div ui-view></div>
</div>
<script>
var app = angular.module('appcrudrouter', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {
    
    $urlRouterProvider.otherwise('/home');
    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'pages/home.html',
            controller: 'homeCtrl'
        })
        .state('add', {
            url: '/add',
            templateUrl: 'pages/add.html',
            controller: 'addCtrl'
        })
        .state('edit', {
            url: '/edit/{member:json}',
            templateUrl: 'pages/edit.html',
            controller: 'editCtrl'
        })
        .state('delete', {
            url: '/delete/{member:json}',
            templateUrl: 'pages/delete.html',
            controller: 'deleteCtrl'
        })
      
	    .state('about', {
            url: '/about',
            templateUrl: 'pages/about.html',
             controller: function($scope) {
                $scope.animals = [{id:1,name:'Dog'},
                {id:2,name:'Cat'}];
            }
        })
		
		.state('about.list', {
            url: '/list/:id',
            templateUrl: 'pages/list.html',
            controller: function($scope,$stateParams) {
                $scope.num = $stateParams.id;
            }
        })
});
</script>
<script src="js/homeController.js"></script>
<script src="js/addController.js"></script>
<script src="js/editController.js"></script>
<script src="js/deleteController.js"></script>
<script src="js/memberService.js"></script>
</body>
</html>
js/addController.js
//js/addController.js
'use strict';

app.controller('addCtrl', ['$scope', 'memberService', '$location', function($scope, memberService, $location){
	$scope.error = false;
	//add member
	$scope.add = function(){
		var addmember = memberService.create($scope.member);
		addmember.then(function(response){
			if(response.data.error){
				$scope.error = true;
				$scope.message = response.data.message;
			}
			else{
				console.log(response);
				$location.path('home');
			}
		});
	}

}]);
js/deleteController.js
//js/deleteController.js
'use strict';

app.controller('deleteCtrl', ['$scope', 'memberService', '$location', '$stateParams', function($scope, memberService, $location, $stateParams){
	$scope.error = false;
	$scope.deletemember = $stateParams.member;

	//delete member
	$scope.delete = function(){
		var dmember = memberService.delete($scope.deletemember);
		dmember.then(function(response){
			if(response.data.error){
				$scope.error = true;
				$scope.message = response.data.message;
			}
			else{
				console.log(response);
				$location.path('home');
			}
		});
	}
}]);
js/editController.js
//js/editController.js
'use strict';

app.controller('editCtrl', ['$scope', 'memberService', '$location', '$stateParams', function($scope, memberService, $location, $stateParams){
	$scope.error = false;
	$scope.updatedmember = $stateParams.member;

	//edit member
	$scope.update = function(){
		var updatemember = memberService.update($scope.updatedmember);
		updatemember.then(function(response){
			console.log(response);
			if(response.data.error){
				$scope.error = true;
				$scope.message = response.data.message;
			}
			else{
				console.log(response);
				$location.path('home');
			}
		});
	}

}]);
js/homeController.js
//js/homeController.js
'use strict';

app.controller('homeCtrl', ['$scope', 'memberService', function($scope, memberService){
	//fetch members
	$scope.fetch = function(){
		var members = memberService.read();
		members.then(function(response){
			$scope.members = response.data;
		});
	}

}]);
js/memberService.js
//js/memberService.js
'use strict';

app.factory('memberService', function($http){
	return{
		read: function(){
			var read = $http.get('api/read.php');
			return read;
		},
		create: function(member){
			var add = $http.post('api/add.php', member);
			return add;
		},
		update: function(member){
			var edit = $http.post('api/edit.php', member);
			return edit;
		},
		delete: function(member){
			var del = $http.post('api/delete.php', member);
			return del;
		}
	}
});
pages/home.html
//pages/home.html
<div class="row" ng-init="fetch()">
	<div class="col-md-12">
		<button href="" class="btn btn-primary" ui-sref="add"><i class="fa fa-plus"></i> Add New</button>	
		<table class="table table-bordered table-striped" style="margin-top:10px;">
			<thead>
                <tr>
                    <th>Firstname</th>
                   	<th>Lastname</th>
                    <th>Address</th>
                   	<th width="200">Action</th>
                </tr>
            </thead>
			<tbody>
				<tr ng-repeat="member in members">
					<td>{{ member.firstname }}</td>
					<td>{{ member.lastname }}</td>
					<td>{{ member.address }}</td>
					<td>
						<button type="button" class="btn btn-success" ui-sref="edit({member: member})"><i class="fa fa-edit"></i> Edit</button> 
						<button type="button" class="btn btn-danger" ui-sref="delete({member: member})"> <i class="fa fa-trash"></i> Delete</button>
					</td>
				</tr>
			</tbody>
		</table>
	</div>
</div>
pages/add.html
//pages/add.html
<div class="row">
	<div class="col-sm-6">
		<div class="alert alert-danger text-center" ng-show="error">
			<button type="button" class="close" ng-click="clear()"><span aria-hidden="true">×</span></button>
			<i class="fa fa-warning"></i> {{ message }}
		</div>
		<div class="panel panel-default">
			<div class="panel-body">
				<h3 class="text-center">Add Form</h3>
				<div class="form-group">
					<label>Firstname:</label>
					<input type="text" class="form-control" ng-model="member.firstname">
				</div>
				<div class="form-group">
					<label>Lastname:</label>
					<input type="text" class="form-control" ng-model="member.lastname">
				</div>
				<div class="form-group">
					<label>Address:</label>
					<input type="text" class="form-control" ng-model="member.address">
				</div>
				<button type="button" class="btn btn-primary" ng-click="add()"><i class="fa fa-save"></i> Save</button>
				<button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
			</div>
		</div>
	</div>
</div>
pages/edit.html
//pages/edit.html
<div class="row">
	<div class="col-sm-6">
		<div class="alert alert-danger text-center" ng-show="error">
			<button type="button" class="close" ng-click="clear()"><span aria-hidden="true">×</span></button>
			<i class="fa fa-warning"></i> {{ message }}
		</div>
		<div class="panel panel-default">
			<div class="panel-body">
				<h3 class="text-center">Edit Form</h3>
				<div class="form-group">
					<label>Firstname:</label>
					<input type="text" class="form-control" ng-model="updatedmember.firstname">
				</div>
				<div class="form-group">
					<label>Lastname:</label>
					<input type="text" class="form-control" ng-model="updatedmember.lastname">
				</div>
				<div class="form-group">
					<label>Address:</label>
					<input type="text" class="form-control" ng-model="updatedmember.address">
				</div>
				<button type="button" class="btn btn-success" ng-click="update()"><i class="fa fa-check-square-o"></i> Update</button>
				<button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
			</div>
		</div>
	</div>
</div>
pages/delete.html
//pages/delete.html
<div class="row">
    <div class="col-sm-6">
        <div class="alert alert-danger text-center" ng-show="error">
            <button type="button" class="close" ng-click="clear()"><span aria-hidden="true">×</span></button>
            <i class="fa fa-warning"></i> {{ message }}
        </div>
        <div class="panel panel-default">
            <div class="panel-body">
                <h4 class="text-center">Are you sure you want to delete</h4>
                <h3 class="text-center">{{ deletemember.firstname + ' ' + deletemember.lastname }}</h3><br>
                <button type="button" class="btn btn-danger" ng-click="delete()"><i class="fa fa-trash"></i> Delete</button>
                <button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
            </div>
        </div>
    </div>
</div>
pages/about.html
//pages/about.html
<div>
    <h1>About Page</h1>
    <p>This page demonstrates <span class="text-danger">multiple</span> and <span class="text-danger">named</span> views.</p>
</div>
<div class="row">
       <ul>
        <li ng-repeat="an in animals">
            <a ui-sref="about.list({id:an.id})">{{an.name}}</a>
        </li>
    </ul>
	<div ui-view></div>
</div>
pages/list.html
//pages/list.html
<div ng-if="num == 1"><strong>Dog</strong> is clicked</div>
<div ng-if="num == 2"><strong>Cat</strong> is clicked</div>
api/add.php
//api/add.php
<?php
    include('dbcon.php');
    
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false, 'firstname' => false, 'lastname' => false, 'address' => false);

    $firstname = $data->firstname;
    $lastname = $data->lastname;
    $address = $data->address;

    if(empty($firstname)){
        $out['firstname'] = true;
        $out['message'] = 'Firstname is required'; 
    } 
    elseif(empty($lastname)){
        $out['lastname'] = true;
        $out['message'] = 'Lastname is required'; 
    }
    elseif(empty($address)){
        $out['address'] = true;
        $out['message'] = 'Address is required'; 
    }
    else{
        $sql = "INSERT INTO members (firstname, lastname, address) VALUES ('$firstname', '$lastname', '$address')";
        $query = $conn->query($sql);

        if($query){
            $out['message'] = 'Member Added Successfully';
        }
        else{
            $out['error'] = true;
            $out['message'] = 'Cannot Add Member';
        }
    }
        
    echo json_encode($out);
?>
api/read.php
//api/read.php
<?php
	include('dbcon.php');
	
	$out = array();
	$sql = "SELECT * FROM members";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$out[] = $row;
	}

	echo json_encode($out);
?>
api/edit.php
//api/edit.php
<?php
    include('dbcon.php');
    
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false);

    $firstname = $data->firstname;
    $lastname = $data->lastname;
    $address = $data->address;
    $memid = $data->id;

   	$sql = "UPDATE members SET firstname = '$firstname', lastname = '$lastname', address = '$address' WHERE id = '$memid'";
   	$query = $conn->query($sql);

   	if($query){
   		$out['message'] = 'Member updated Successfully';
   	}
   	else{
   		$out['error'] = true;
   		$out['message'] = 'Cannot update Member';
   	}

    echo json_encode($out);
?>
api/delete.php
//api/delete.php
<?php
    include('dbcon.php');
    
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false);

    $memid = $data->id;

   	$sql = "DELETE FROM members WHERE id = '$memid'";
   	$query = $conn->query($sql);

   	if($query){
   		$out['message'] = 'Member deleted Successfully';
   	}
   	else{
   		$out['error'] = true;
   		$out['message'] = 'Cannot delete Member';
   	}

    echo json_encode($out);
?>
api/dbcon.php
//api/dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Monday, December 6, 2021

SwiftUI Simple Alert and Confirmation Dialog

SwiftUI Simple Alert and Confirmation Dialog

ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var deleteConfirm = false
    @State private var showingOptions = false
    @State private var selection = "None"
    
    var body: some View {
        VStack {
            Button {
                self.deleteConfirm.toggle()
            } label: {
                Label("Delete", systemImage: "trash.fill")
            }
            .buttonStyle(.bordered)
            .tint(.red)
            .controlSize(.regular)
            //.alert("Are you Sure you want to delete?", isPresented: self.$deleteConfirm) {
            //    Button("Delete", role: .destructive) {
            //        print("Deleted")
            //    }
            //}
            .confirmationDialog("Are you Sure you want to delete?", isPresented: self.$deleteConfirm, titleVisibility: .visible) {
                Button("Delete", role: .destructive) {
                    print("Deleted")
                }
            }
            
            Text(selection)

            Button("Confirm paint color") {
                showingOptions = true
            }
            .buttonStyle(.bordered)
            .tint(.red)
            .controlSize(.regular)
            
            .confirmationDialog("Select a color", isPresented: $showingOptions, titleVisibility: .visible) {
                Button("Red") {
                    selection = "Red"
                }

                Button("Green") {
                    selection = "Green"
                }

                Button("Blue") {
                    selection = "Blue"
                }
            }
            

        }
    }
}

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

Saturday, December 4, 2021

AngularJS Load more data with PHP MySQLi

AngularJS Load more data with PHP MySQLi

CREATE TABLE `posts` (
  `id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `posts` (`id`, `title`, `content`, `link`, `timestamp`) VALUES
(4, 'What is AngularJS', 'AngularJS is a JavaScript MVC framework  developed by Google that lets you build well structured, easily testable,  declarative and maintainable front-end applications which provides solutions to  standard infrastructure concerns.', 'link-5', '2021-03-20 08:00:00'),
(5, 'What is MongoDB', 'It is a quick tutorial on MongoDB and how you can install it on your Windows OS. We will also learn some basic commands in MongoDB for example, creating and dropping a Database, Creation of a collection and some more operations related to the collection.', 'link-6', '2021-03-21 08:00:00'),
(6, 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'link-6', '2021-03-20 08:00:00'),
(7, 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'link-7', '2021-03-14 08:00:00'),
(8, 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'link-8', '2021-03-20 08:00:00'),
(9, 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'link-9', '2021-03-19 08:00:00'),
(10, 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'link-10', '2021-03-15 08:00:00'),
(11, 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'link-11', '2021-03-14 08:00:00');

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

ALTER TABLE `posts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AngularJS Load more data with PHP MySQLi</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
</head>
<body ng-app="app" ng-controller="myController" ng-init="fetch()">
<div class="container">
    <h1 class="page-header text-center">AngularJS Load more data with PHP MySQLi</h1>
	<div class="col-md-12">
	    <div class="panel panel-default" ng-repeat="rs in posts">
	    	<div class="panel-body">
	    		<span style="font-size:20px">{{ rs.id }} {{ rs.title }}</span>
	    	</div>
		</div>
		<button class="btn btn-success btn-lg btn-block" ng-click="loadmore()">{{ loadName }}</button>
		<br><br>
	</div>
</div>
<script>
var app = angular.module('app', []);
app.controller('myController', function($scope, $http){
	$scope.loadName = 'Load More';
	$scope.fetch = function(){
    	$http.get('fetch.php')
    	.success(function(data){ 
    	    $scope.posts = data;
    	    console.log($scope.posts); 
	    });
    }

    $scope.loadmore = function(){
    	var lastid = $scope.posts.length - 1;
    	var lastobj = $scope.posts[lastid];
    	$http.post('loadmore.php', lastobj)
    	.success(function(data){ 
    		if(data == ''){
    			$scope.loadName = 'No more Data to Load';
    		}
    		else{
    			angular.forEach(data, function(newpost){
					$scope.posts.push(newpost); 
				});
    		}
    	    console.log($scope.posts);
	    });
    }
});
</script>
</body>
</html>
fetch.php
//fetch.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');
	
	$output = array();
	$sql = "SELECT * FROM posts ORDER BY id ASC LIMIT 3";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>
loadmore.php
//loadmore.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');

	$data = json_decode(file_get_contents('php://input'));
	
	$output = array();

	$id = $data->id;

	$sql = "SELECT * FROM posts WHERE id > '$id' ORDER BY id ASC LIMIT 3";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>

Friday, December 3, 2021

Vue.js Axios Dropdown Select Box Search with PHP Mysql and Vue Select

Vue.js Axios Dropdown Select Box Search with PHP Mysql and Vue Select

https://vue-select.org/

Vue Select is a feature rich select/dropdown/typeahead component. It provides a default template that fits most use cases for a filterable select dropdown.

https://vue-select.org/guide/install.html

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 `country` (
  `id` int(6) NOT NULL,
  `country` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<title>Vue.js Axios Dropdown Select Box Search with PHP Mysql</title>
	<link rel="stylesheet" href="https://unpkg.com/vue-select@3.0.0/dist/vue-select.css">
</head>
<body>
<div id="app">
	<p><h1>Vue.js Axios Dropdown Select Box Search with PHP Mysql and Vue Select </h1></p>
	<div style="width:500px;">
	<p>Countries : <v-select v-model="country" label="name" :reduce="country => country.id" :options="country_options" @search="fetchOptions" @input="selectedOption"  >
	</v-select> </p>
	<p>Selected Value : <span v-text="country"></span></p>
	</div>
</div>
<script src="https://unpkg.com/vue@latest"></script>
<script src="https://unpkg.com/vue-select@latest"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
Vue.component('v-select', VueSelect.VueSelect)

	new Vue({
	  	el: '#app',
	  	data: {
		  	country: 0,
		    country_options: []
	  	},
	  	methods: {
	  		fetchOptions: function(search){
      			
      			var el = this;

      			// AJAX request
	  			axios.get('select.php', {
	                params: {
						search: search,		
					}
	            })
	            .then(function (response) {
	               	
	               	// Update options
	                el.country_options = response.data; 
	                  
	            });

	  		},
	  		selectedOption: function(value){
	  			console.log("value : " + value);
	  		}
	  	}
	})
	</script>
</body>
</html>
select.php
//select.php
<?php
$host = "localhost"; 
$user = "root";
$password = ""; 
$dbname = "testingdb"; 

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

$search = "";
if(isset($_GET['search'])){
	$search = mysqli_real_escape_string($con,$_GET['search']);
}

$query = 'SELECT * FROM country where country like "%'.$search.'%" ';
$result = mysqli_query($con,$query);

$response_arr = array();
 
while($datarow = mysqli_fetch_assoc($result)){
 
    $id = $datarow['id'];
    $name = $datarow['country'];
  
    $response_arr[] = array(
    	"id"=> $id,
    	"name" => $name
    );
 	
}

echo json_encode($response_arr);
exit;

SwiftUI Welcome Page and Sign In Page UI Design

SwiftUI Welcome Page and Sign In Page UI Design

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUITest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            ZStack {
                Color("BgColor").edgesIgnoringSafeArea(.all)
                VStack {
                    Spacer()
                    Image("home")
                    Spacer()
                    PrimaryButton(title: "Get Started")
                    
                    NavigationLink(
                        destination: SignInView().navigationBarHidden(true),
                        label: {
                            Text("Sign In")
                                .font(.title3)
                                .fontWeight(.bold)
                                .foregroundColor(Color("PrimaryColor"))
                                .padding()
                                .frame(maxWidth: .infinity)
                                .background(Color.white)
                                .cornerRadius(50.0)
                                .shadow(color: Color.black.opacity(0.08), radius: 60, x: 0.0, y: 16)
                                .padding(.vertical)
                        })
                        .navigationBarHidden(true)
                    
                    HStack {
                        Text("New around here? ")
                        Text("Sign in")
                            .foregroundColor(Color("PrimaryColor"))
                    }
                }
                .padding()
            }
        }
    }
}

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

struct PrimaryButton: View {
    var title: String
    var body: some View {
        Text(title)
            .font(.title3)
            .fontWeight(.bold)
            .foregroundColor(.white)
            .frame(maxWidth: .infinity)
            .padding()
            .background(Color("PrimaryColor"))
            .cornerRadius(50)
    }
}
SignInView.swift
 
//
//  SignInView.swift
//  SwiftUITest
//
//  Created by Cairocoders
//

import SwiftUI

struct SignInView: View {
    @State private var email: String = "" // by default it's empty
    var body: some View {
        ZStack {
            Color("BgColor").edgesIgnoringSafeArea(.all)
            VStack {
                Spacer()
                
                VStack {
                    Text("Sign In")
                        .font(.largeTitle)
                        .fontWeight(.bold)
                        .padding(.bottom, 30)
                    
                    SocalLoginButton(image: Image(uiImage: #imageLiteral(resourceName: "apple")), text: Text("Sign in with Apple"))
                    
                    SocalLoginButton(image: Image(uiImage: #imageLiteral(resourceName: "google")), text: Text("Sign in with Google").foregroundColor(Color("PrimaryColor")))
                        .padding(.vertical)
                    
                    Text("or get a link emailed to you")
                        .foregroundColor(Color.black.opacity(0.4))
                    
                    TextField("Work email address", text: $email)
                        .font(.title3)
                        .padding()
                        .frame(maxWidth: .infinity)
                        .background(Color.white)
                        .cornerRadius(50.0)
                        .shadow(color: Color.black.opacity(0.08), radius: 60, x: /*@START_MENU_TOKEN@*/0.0/*@END_MENU_TOKEN@*/, y: 16)
                        .padding(.vertical)
                    
                    PrimaryButton(title: "Email me a signup link")
                    
                }
                
                Spacer()
                Divider()
                Spacer()
                Text("You are completely safe.")
                Text("Read our Terms & Conditions.")
                    .foregroundColor(Color("PrimaryColor"))
                Spacer()
                
            }
            .padding()
        }
    }
}

struct SignInView_Previews: PreviewProvider {
    static var previews: some View {
        SignInView()
    }
}

struct SocalLoginButton: View {
    var image: Image
    var text: Text
    
    var body: some View {
        HStack {
            image
                .padding(.horizontal)
            Spacer()
            text
                .font(.title2)
            Spacer()
        }
        .padding()
        .frame(maxWidth: .infinity)
        .background(Color.white)
        .cornerRadius(50.0)
        .shadow(color: Color.black.opacity(0.08), radius: 60, x: /*@START_MENU_TOKEN@*/0.0/*@END_MENU_TOKEN@*/, y: 16)
    }
}

Related Post