article

Thursday, February 24, 2022

PHP Mysqli Simple Login Session with Validation

PHP Mysqli Simple Login Session with Validation

CREATE TABLE `userlogin` (
  `userid` int(11) NOT NULL,
  `username` varchar(30) NOT NULL,
  `password` varchar(30) NOT NULL,
  `fullname` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `userlogin` (`userid`, `username`, `password`, `fullname`) VALUES
(1, 'cairocoders', '123456', 'Cairocoders Ednalan');

ALTER TABLE `userlogin`
  ADD PRIMARY KEY (`userid`);

ALTER TABLE `userlogin`
  MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>PHP Mysqli Simple Login Session with Validation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />  
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.message {color: #FF0000;}
</style>
</head>
<body>
<?php
$Message = $ErrorUname = $ErrorPass = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  
    $username = check_input($_POST["username"]);
	
    if (!preg_match("/^[a-zA-Z0-9_]*$/",$username)) {
      $ErrorUname = "Space and special characters not allowed but you can use underscore(_)."; 
    }
	else{
		$fusername=$username;
	}
 
	$fpassword = check_input($_POST["password"]);

  if ($ErrorUname!=""){
	$Message = "Login failed! Errors found";
  }
  else{
  include('conn.php');
  
  $query=mysqli_query($conn,"select * from userlogin where username='$fusername' && password='$fpassword'");
  $num_rows=mysqli_num_rows($query);
  $row=mysqli_fetch_array($query);
  
  if ($num_rows>0){
	  $Message = "Login Successful!";
  }
  else{
	$Message = "Login Failed! User not found";
  }
  
  }
}

function check_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>
<section class="login">
<div class="container">
	<div class="row justify-content-center">
		<div class="col-md-6 text-center mb-5">
			<h2 class="heading-section">PHP Mysqli Simple Login Session with Validation</h2>
		</div>
	</div>
	<div class="row justify-content-center">
		<div class="col-md-7 col-lg-5">
			<div class="p-4 p-md-5">
			<div class="d-flex">
				<div class="w-100">
				<h3 class="mb-4">Sign In</h3>
				</div>
				<div class="w-100">
				<p class="justify-content-end">
				<a href="#" class="align-items-center justify-content-center"><span class="fa fa-facebook"></span></a>
				<a href="#" class="align-items-center justify-content-center"><span class="fa fa-twitter"></span></a>
				</p>
				</div>
			</div>
			<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
				<p><span class="message">* required field.</span></p>
				<div class="form-group mt-3">
					<input type="text" name="username" class="form-control" required>
					<label class="form-control-placeholder" for="username">Username</label>
					<span class="message">* <?php echo $ErrorUname;?></span>
				</div>
				<div class="form-group">
					<input type="password" name="password" class="form-control" required>
					<label class="form-control-placeholder" for="password">Password</label>
					<span class="message">* <?php echo $ErrorPass;?></span>
					<span class="fa fa-fw fa-eye"></span>
				</div>
				<div class="form-group">
					<button type="submit" class="form-control btn btn-primary rounded submit px-3">Sign In</button>
				</div>
				<span class="message">
				<?php
					if ($Message=="Login Successful!"){
						echo $Message;
						echo 'Welcome, '.$row['fullname'];
					}
					else{
						echo $Message;
					}

				?>
				</span>
				<div class="form-group d-md-flex">
					<div class="w-50 text-left">
					<label class="checkbox-primary mb-0">Remember Me
					<input type="checkbox" checked>
					<span class="checkmark"></span>
					</label>
					</div>
					<div class="w-50 text-md-right">
					<a href="#">Forgot Password</a>
					</div>
				</div>
			</form>
			<p class="text-center">Not a member? <a data-toggle="tab" href="#signup">Sign Up</a></p>
			</div>
		</div>
	</div>
</div>
</section>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

SwiftUI ScrollView Sticky Header

SwiftUI ScrollView Sticky Header

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            StickyHeader {
                StickyHeader {
                    Image("3")
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                }
            }
            
            HStack(alignment: .center) {
                VStack {
                    Text("Taylor")
                        .padding()
                        .font(.title)
                    Text("Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..")
                        .padding()
                    Image("1")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .padding(.all, 20)
                    
                    Text("Caitelyn")
                        .padding()
                        .font(.title)
                    
                    Image("2")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .padding(.all, 20)
                
                }.padding(10)
            }
            .frame(maxWidth: .infinity, alignment: .center)
            .background(Color.white)
            .modifier(CardModifier())
            .padding(.all, 10)
            
        }
    }
}

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

struct StickyHeader<Content: View>: View {

    var minHeight: CGFloat
    var content: Content
    
    init(minHeight: CGFloat = 200, @ViewBuilder content: () -> Content) {
        self.minHeight = minHeight
        self.content = content()
    }
    
    var body: some View {
        GeometryReader { geo in
            if(geo.frame(in: .global).minY <= 0) {
                content
                    .frame(width: geo.size.width, height: geo.size.height, alignment: .center)
            } else {
                content
                    .offset(y: -geo.frame(in: .global).minY)
                    .frame(width: geo.size.width, height: geo.size.height + geo.frame(in: .global).minY)
            }
        }.frame(minHeight: minHeight)
    }
}

struct CardModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .cornerRadius(20)
            .shadow(color: Color.black.opacity(0.2), radius: 20, x: 0, y: 0)
    }
    
}

Wednesday, February 23, 2022

Vue CLI How to use Vue Router

Vue CLI How to use Vue Router

# Create a new Vue project
vue create myapp
cd myapp
# start your app by running the following command
npm run serve

vue add router

C:\vuejs\myapp>vue add router

src/router/index.js
//src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Profile from '../views/Profile.vue'
import Product from '../views/Product.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/profile',
    name: 'profile',
    component: Profile,
  },
  { path: '/product/:id', component: Product },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router
src/App.vue
//src/App.vue
<template>
  <div id="nav">
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link> |
    <!--<router-link to="/profile">Profile</router-link> -->
    <router-link :to="{ name: 'profile', params: { username: 'cairocoders' } }" > <!--router params -->
      Profile
    </router-link>  |
    <router-link to="/product">Product</router-link> 
  </div>
  <router-view/>
</template>
src/main.js
//src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App).use(router).mount('#app')
src/views/Product.vue
//src/views/Product.vue
<template>
    <div class="product">
        Product Page
    </div>
    <span>
        Looking for Product: {{ this.$route.params.id }}
    </span>
</template>
src/views/Profile.vue
//src/views/Profile.vue
<template>
    <div class="profile">
        Profile Info
    </div>
    <span>
        {{ this.$route.params.username }}
    </span>
</template>

Tuesday, February 22, 2022

SwiftUI Custom Dropdwon Picker

SwiftUI Custom Dropdwon Picker

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var selection = 1
    
    var body: some View {
        VStack {
            ZStack(alignment: .bottomTrailing) {
                Image("coffee").resizable().frame(height: 350)
                HStack(spacing: 15){
                    Text("Kapeng Barako")
                        .foregroundColor(.white)
                    
                }.padding()
            }
             
            Text("Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit")
            
            DropdownPicker(title: "Size", selection: $selection, options: ["Small", "Medium", "Large", "X-Large"])
            
            Button("Place Order") {
                
            }
            .foregroundColor(.white)
            .frame(width: 300, height: 50)
            .background(Color.orange)
            .cornerRadius(10)
            
            Spacer()
            
        }.padding()
    }
}

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

struct DropdownPicker: View {
    
    var title: String
    @Binding var selection: Int
    var options: [String]
    
    @State private var showOptions: Bool = false
    
    var body: some View {
        ZStack {
            // current selection
            HStack {
                Text(title)
                Spacer()
                Text(options[selection])
                    .foregroundColor(Color.black.opacity(0.6))
                Image(systemName: "chevron.right")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 10, height: 10)
            }
            .font(Font.custom("Avenir Next", size: 16).weight(.medium))
            .padding(.horizontal, 12)
            .padding(.vertical, 8)
            .background(Color.white)
            .onTapGesture {
                // show the dropdown options
                withAnimation(Animation.spring().speed(2)) {
                    showOptions = true
                }
            }
            
            // Drop down options
            if showOptions {
                VStack(alignment: .leading, spacing: 4) {
                    Text(title)
                        .font(Font.custom("Avenir Next", size: 16).weight(.semibold))
                        .foregroundColor(.white)
                    HStack {
                        Spacer()
                        ForEach(options.indices, id: \.self) { i in
                            if i == selection {
                                Text(options[i])
                                    .font(.system(size: 12))
                                    .padding(.vertical, 8)
                                    .padding(.horizontal, 12)
                                    .background(Color.white.opacity(0.2))
                                    .cornerRadius(4)
                                    .onTapGesture {
                                        // hide dropdown options - user selection didn't change
                                        withAnimation(Animation.spring().speed(2)) {
                                            showOptions = false
                                        }
                                    }
                            } else {
                                Text(options[i])
                                    .font(.system(size: 12))
                                    .onTapGesture {
                                        // update user selection and close options dropdown
                                        withAnimation(Animation.spring().speed(2)) {
                                            selection = i
                                            showOptions = false
                                        }
                                    }
                            }
                            Spacer()
                        }
                    }
                    .padding(.vertical, 2)
                    .transition(AnyTransition.move(edge: .top).combined(with: .opacity))
                    
                }
                .padding(.horizontal, 12)
                .padding(.vertical, 8)
                .background(Color.black)
                .foregroundColor(.white)
                .transition(.opacity)
                
            }
            
        }
    }
}

Monday, February 21, 2022

SwiftUI View Profile Page - Sheets and ForEach

SwiftUI View Profile Page - Sheets and ForEach

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var data: userlist?
    
    var body: some View {
        NavigationView {
            
            VStack {
                HStack(spacing: 16) {
                    Image("pic")
                        .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) {
                        Text("cairocoders")
                            .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 {
                        
                    } label: {
                        Image(systemName: "gear")
                            .font(.system(size: 24, weight: .bold))
                            .foregroundColor(Color(.label))
                    }
                }//End HStack
                .padding()
                
                ScrollView {
                    ForEach(user){i in
                        Button(action: {
                            data = .init(id: i.id, name: i.name, image: i.image, pic: i.pic)
                        }) {
                            VStack {
                                HStack(spacing: 16) {
                                    Image(i.image)
                                        .resizable()
                                        .scaledToFill()
                                        .frame(width: 50, height: 50)
                                        .clipped()
                                        .cornerRadius(50)
                                    
                                    VStack(alignment: .leading) {
                                        Text(i.name)
                                            .font(.system(size: 16, weight: .bold))
                                        Text("View Profile")
                                            .font(.system(size: 14))
                                            .foregroundColor(Color(.lightGray))
                                    }
                                    Spacer()
                                    
                                    Text("22m")
                                        .font(.system(size: 14, weight: .semibold))
                                }
                                Divider()
                                .padding(.vertical, 8)
                                
                            }.padding(.horizontal)
                        }
                    }//End ForEach
                    .padding(.bottom, 50)
                    .sheet(item: $data) { rs in
                        Profile(viewdata: rs)
                    }
                }// End scrollview
            }
            .navigationBarHidden(true)
        }
    }
}

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


struct userlist : Identifiable {
     
    var id : Int
    var name : String
    var image : String
    var pic : String
}

var user = [
    userlist(id: 0, name: "Taylor", image: "photo1", pic: "1"),
    userlist(id: 1, name: "Mari", image: "photo2", pic: "2"),
    userlist(id: 2, name: "Sandra", image: "photo3", pic: "3")
]
Profile.swift
 
//
//  Profile.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct Profile : View {
    
    @Environment(\.presentationMode) var presentationMode
    
    let viewdata : userlist
    
    var body : some View{
        
        ZStack{
            Image(viewdata.pic).resizable().edgesIgnoringSafeArea(.all)
            
            VStack{
                HStack{
                    
                    Button(action: {
                    }) {
                        Image(systemName: "slider.horizontal.3").foregroundColor(Color.black).font(.title)
                    }
                    
                    Spacer()
                    
                    Button(action: {
                        presentationMode.wrappedValue.dismiss()
                    }) {
                        Image(systemName: "xmark").foregroundColor(Color.black).font(.title)
                    }
                }
                
                Spacer()
                
                ZStack(alignment: .top) {
                    VStack{
                        HStack{
                            VStack(alignment: .leading, spacing: 10) {
                                
                                Text("\(viewdata.name),").font(.title)
                                Text("19")
                            }
                            
                            Spacer()
                            
                            HStack(spacing: 8){
                                Image(systemName: "mappin.and.ellipse")
                                
                                Text("2 Miles")
                                
                            }.padding(8)
                            .background(Color.black.opacity(0.1))
                            .cornerRadius(10)
                            
                        }.padding(.top,35)
                        
                        Text("Hi! My name \(viewdata.name). I like sharing my thoughts and adore people who except me the way I am. Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.").padding(.top)
                        
                    }.padding()
                    .background(Blurview())
                    .clipShape(BottomShape())
                    .cornerRadius(25)
                    
                    ZStack{
                        Button(action: {
                        }) {
                            Image(systemName: "message.and.waveform")
                                .frame(width: 20, height: 20)
                                .padding(20)
                                .background(Color.white)
                                .clipShape(Circle())
                                .font(.title)
                                .foregroundColor(Color.green)
                        }
                        
                        Circle().stroke(Color.green, lineWidth: 5).frame(width: 70, height: 70)
                        
                    }.offset(y: -35)
                    
                    HStack{
                        Button(action: {
                            
                        }) {
                            Image(systemName: "suit.heart")
                                .frame(width: 25, height: 20)
                                .padding()
                                .background(Color.white)
                                .clipShape(Circle())
                                .font(.title)
                                .foregroundColor(Color.red)
                        }
                        
                        Spacer()
                        
                        Button(action: {
                            
                        }) {
                            Image(systemName: "hand.thumbsup")
                                .frame(width: 25, height: 25)
                                .padding()
                                .background(Color.white)
                                .clipShape(Circle())
                                .font(.title)
                                .foregroundColor(Color.blue)
                        }
                        
                    }.offset(y: -25)
                    .padding(.horizontal,35)
                        
                }
            }.padding()
        }
    }
}

struct BottomShape : Shape {
    
    func path(in rect: CGRect) -> Path {
        
        return Path{path in

            path.move(to: CGPoint(x: 0, y: 0))
            path.addLine(to: CGPoint(x: 0, y: rect.height))
            path.addLine(to: CGPoint(x: rect.width, y: rect.height))
            path.addLine(to: CGPoint(x: rect.width, y: 0))
            path.addArc(center: CGPoint(x: rect.width / 2, y: 0), radius: 42, startAngle: .zero, endAngle: .init(degrees: 180), clockwise: false)
            
        }
    }
}

struct Blurview : UIViewRepresentable {
    
    func makeUIView(context: UIViewRepresentableContext<Blurview>) -> UIVisualEffectView {
        
        let view = UIVisualEffectView(effect: UIBlurEffect(style: .systemUltraThinMaterialLight))
        
        return view
    }
    
    func updateUIView(_ uiView: UIVisualEffectView, context: UIViewRepresentableContext<Blurview>) {
        
    }
}

struct Profile_Previews: PreviewProvider {
    static var previews: some View {
        Profile(viewdata: userlist(id: 1, name: "Taylor", image: "photo1", pic: "1"))
    }
}

Sunday, February 20, 2022

SwiftUI Show Model Data to Sheet - Sheets and ForEach

SwiftUI Show Model Data to Sheet - Sheets and ForEach

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

import SwiftUI
 
struct ContentView : View {
     
    @State var fruit: Fruits?
    
    var body: some View {
        VStack(spacing: 20) {
            ForEach(post) { i in
                Button(i.title) {
                    fruit = .init(id: i.id, title: i.title, price: i.price)
                }
                .foregroundColor(.white)
                .frame(width: 300, height: 50)
                .background(Color.orange)
                .cornerRadius(10)
                .sheet(item: $fruit) { rs in
                    DetailsView(viewdata: rs)
                }
            }
        }
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct DetailsView: View {

    @State var viewdata: Fruits
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        
        VStack {
            Button("Dismiss") {
                presentationMode.wrappedValue.dismiss()
            }
            Spacer()
            Text(viewdata.title)
                .font(.title)
            Text(viewdata.price)
                .font(.title)
            Spacer()
        }
    }
}

struct Fruits: Identifiable {

    let id: Int
    let title: String
    let price : String
}

var post = [
    Fruits(id: 0, title: "Strawberry", price: "45"),
    Fruits(id: 1, title: "Pineapples", price: "89"),
    Fruits(id: 2, title: "Apple", price: "5"),
    Fruits(id: 3, title: "Watermelon", price: "10"),
    Fruits(id: 4, title: "Orange", price: "32"),
    Fruits(id: 5, title: "Banana", price: "56")
]

Saturday, February 19, 2022

JavaScript PHP upload multiple files

JavaScript PHP upload multiple files

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<title>JavaScript PHP upload multiple files</title>
</head>
<body>
	<div>
		<p><h1>JavaScript PHP upload multiple files<h1></p>
		<input type="file" name="files" id="files" multiple>
		<input type="button" id="btn_uploadfile" value="Upload" onclick="uploadFile();">
	</div>

<script type="text/javascript">
	function uploadFile() {

		var totalfiles = document.getElementById('files').files.length;
		
		if(totalfiles > 0 ){ 

			var formData = new FormData();
			
			// Read selected files
		   	for (var index = 0; index < totalfiles; index++) {
		      	formData.append("files[]", document.getElementById('files').files[index]);
		   	}

			var xhttp = new XMLHttpRequest();

			// Set POST method and ajax file path
			xhttp.open("POST", "ajaxfile.php", true);

			// call on request changes state
			xhttp.onreadystatechange = function() {
			    if (this.readyState == 4 && this.status == 200) {
			      	
			      	var response = this.responseText;

			      	alert(response + " File uploaded.");
			      	
			    }
			};
			
			// Send request with data
			xhttp.send(formData);

		}else{
			alert("Please select a file");
		}
		
	}
</script>
</body>
</html>
ajaxfile.php
//ajaxfile.php
<?php 
// Count total files
$countfiles = count($_FILES['files']['name']);

// Upload directory
$upload_location = "uploads/";
    
$count = 0;
for($i=0;$i<$countfiles;$i++){

	// File name
    $filename = $_FILES['files']['name'][$i];

    // File path
	$path = $upload_location.$filename;

    // file extension
	$file_extension = pathinfo($path, PATHINFO_EXTENSION);
	$file_extension = strtolower($file_extension);

	// Valid file extensions
	$valid_ext = array("pdf","doc","docx","jpg","png","jpeg");

	// Check extension
	if(in_array($file_extension,$valid_ext)){

		// Upload file
		if(move_uploaded_file($_FILES['files']['tmp_name'][$i],$path)){
		    $count += 1;
		}	
	}
                 
}

echo $count;
exit;

Thursday, February 17, 2022

Vue.js Vue CLI Image Upload Preview

Vue.js Vue CLI Image Upload Preview

C:\vuejs\my-vue-app>npm run serve

src/App.vue
//src/App.vue
<template>
  <div id="app">
    <h1>Vue.js Vue CLI Image Upload Preview</h1>
    <HelloWorld/>
  </div>
</template>

<script>
import HelloWorld from './components/filePreview.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
src/components/filePreview.vue
//src/components/filePreview.vue
<template>
  <div>
    <div class="imagePreviewWrapper" :style="{ 'background-image': `url(${previewImage})` }" @click="selectImage"> </div>

    <input ref="fileInput" type="file" @input="pickFile">
  </div>
</template>

<script>
export default {
  data() {
      return {
        previewImage: null
      };
    },
  methods: {
      selectImage () {
          this.$refs.fileInput.click()
      },
      pickFile () {
        let input = this.$refs.fileInput
        let file = input.files
        if (file && file[0]) {
          let reader = new FileReader
          reader.onload = e => {
            this.previewImage = e.target.result
          }
          reader.readAsDataURL(file[0])
          this.$emit('input', file[0])
        }
      }
  }
}
</script>

<style>
.imagePreviewWrapper {
    width: 250px;
    height: 250px;
    display: block;
    cursor: pointer;
    margin: 0 auto 30px;
    background-size: cover;
    background-position: center center;
}
</style>

SwiftUI Floating Tab Bar

SwiftUI Floating Tab Bar

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var selected = 0
    
    var body: some View {
    
        ZStack(alignment: .bottom){
            
            VStack{
                
                if self.selected == 0{
                    GeometryReader{_ in
                        VStack(spacing: 15){
                            Spacer()
                            Text("Home")
                                .font(.title)
                                .foregroundColor(.white)
                            Image("1").resizable().frame(height: 250).cornerRadius(15)
                            Spacer()
                        }.padding()
                    }
                }
                else if self.selected == 1{
                    GeometryReader{_ in
                        VStack(spacing: 15){
                            Spacer()
                            Text("Wishlist")
                                .font(.title)
                                .foregroundColor(.white)
                            Image("2").resizable().frame(height: 250).cornerRadius(15)
                            Spacer()
                        }.padding()
                    }
                }
                else{
                    GeometryReader{_ in
                        VStack(spacing: 15){
                            Spacer()
                            Text("Cart")
                                .font(.title)
                                .foregroundColor(.white)
                            Image("3").resizable().frame(height: 250).cornerRadius(15)
                            Spacer()
                        }.padding()
                    }
                }
                
            }.background(Color.gray)
            .edgesIgnoringSafeArea(.all)
            
            FloatingTabbar(selected: self.$selected)
        }
    }
}

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

struct FloatingTabbar : View {
    
    @Binding var selected : Int
    @State var expand = false
    
    var body : some View{
        
        HStack{
            
            Spacer(minLength: 0)
            
            HStack{
                if !self.expand{
                    
                    Button(action: {
                        self.expand.toggle()
                    }) {
                        Image(systemName: "arrow.left").foregroundColor(.green).padding()
                    }
                }
                else{
                    Button(action: {
                        self.selected = 0
                    }) {
                        Image(systemName: "house").foregroundColor(self.selected == 0 ? .green : .gray).padding(.horizontal)
                    }
                    
                    Spacer(minLength: 15)
                    
                    Button(action: {
                        self.selected = 1
                    }) {
                        Image(systemName: "suit.heart").foregroundColor(self.selected == 1 ? .green : .gray).padding(.horizontal)
                    }
                    
                    Spacer(minLength: 15)
                    
                    Button(action: {
                        self.selected = 2
                    }) {
                        Image(systemName: "cart").foregroundColor(self.selected == 2 ? .green : .gray).padding(.horizontal)
                    }
                }
            }.padding(.vertical,self.expand ? 20 : 8)
            .padding(.horizontal,self.expand ? 35 : 8)
            .background(Color.white)
            .clipShape(Capsule())
            .padding(22)
            .onLongPressGesture {
                    
                    self.expand.toggle()
            }
            .animation(.interactiveSpring(response: 0.6, dampingFraction: 0.6, blendDuration: 0.6))
        }
    }
}

Wednesday, February 16, 2022

SwiftUI UnSpash App UI

SwiftUI UnSpash App UI

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

import SwiftUI

struct ContentView : View {
    
    @State var tabs = ["Wallpapers","Architecture","Nature","People", "Fashion", "Film", "Food & Drink", "Health & Wellnes"]
    @State var txt = ""
    @State var selectedTab = "Nature"
    
    @State var selectedData : [[String]] = [["n1","n2"],["n3","n4"],["n5","n6"]]
    
    @State var wallpaper = [["w1","w2"],["w3","w4"]]
    @State var architecture = [["a1","a2"],["a3","a4"]]
    @State var nature = [["n1","n2"],["n3","n4"],["n5","n6"]]
    @State var people = [["p1","p2"],["p3","p4"]]
    
    var body : some View{
        
        VStack{
            HStack{
                Button(action: {
                    
                }) {
                    Image(systemName: "slider.horizontal.3")
                }
                
                Spacer()
                
                Button(action: {
                    
                }) {
                    Image("logo").renderingMode(.original).resizable().frame(width: 25, height: 25)
                }
                
            }.padding()
            .background(Color.white)
            .overlay(Image("unsplash").renderingMode(.original).resizable().frame(width: 150, height: 25))
            
            ScrollView(.vertical, showsIndicators: false) {
                VStack(alignment: .leading, spacing: 15) {
                    HStack{
                        Image(systemName: "magnifyingglass")
                        TextField("Search", text: self.$txt)
                    }.padding(12)
                    .background(Color("Color"))
                    .clipShape(Capsule())
                    
                    ZStack(alignment: .bottomTrailing) {
                        Image("main").resizable().frame(height: 350)
                        HStack(spacing: 15){
                            Button(action: {
                                
                            }) {
                                Image(systemName: "plus.circle").foregroundColor(Color.white)
                            }
                            
                            Button(action: {
                                
                            }) {
                                Image(systemName: "suit.heart").foregroundColor(Color.white)
                            }
                            
                            Button(action: {
                                
                            }) {
                                Image(systemName: "square.and.arrow.down").foregroundColor(Color.white)
                            }
                            
                        }.padding()
                    }
                    
                    Text("Trending").font(.title).padding(.top)
                    
                    ScrollView(.horizontal, showsIndicators: false) {
                        HStack(spacing: 15){
                            ForEach(tabs,id: \.self){i in
                                
                                Button(action: {
                                    self.selectedTab = i
                                    
                                    if i == "Wallpapers"{
                                        self.selectedData = self.wallpaper
                                        print("Wallpaper")
                                    }
                                    else if i == "Architecture"{
                                         self.selectedData = self.architecture
                                    }
                                    else if i == "Nature"{
                                         self.selectedData = self.nature
                                    }
                                    else{
                                         self.selectedData = self.people
                                    }
                                }) {
                                    VStack{
                                        Text(i).foregroundColor(.black)
                                        
                                        Capsule()
                                            .fill(self.selectedTab == i ? Color.black : Color.clear)
                                            .frame(height: 6)
                                    }
                                }
                            }
                            
                        }.padding(.top)
                    }
                    
                    VStack(spacing: 18){
                        
                        ForEach(selectedData,id: \.self){i in
                            
                            HStack{
                                
                                ForEach(i,id: \.self){j in
                                    
                                    Image(j)
                                        .renderingMode(.original)
                                        .resizable()
                                        .frame(width: UIScreen.main.bounds.width / 2 - 20, height: 180)
                                        .cornerRadius(15)
                                        .contextMenu{
                                            
                                            Button(action: {
                                                UIImageWriteToSavedPhotosAlbum(UIImage(named: j)!, nil, nil, nil)
                                            }) {
                                                HStack{
                                                    Text("Save")
                                                    
                                                    Image(systemName: "arrow.down").resizable().frame(width: 15, height: 15)
                                                }
                                            }
                                        }
                                }
                            }
                        }
                        
                    }.padding(.top)
                }.padding()
            }
        }.background(Color("bg").edgesIgnoringSafeArea(.bottom))
    }
}

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

SwiftUI Firebase Search Bar - Integrating searchable

SwiftUI Firebase Search Bar - Integrating searchable

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

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

import SwiftUI
import Firebase

struct ContentView: View {
    
    @State var search = ""
    
    @ObservedObject var data = getData()
    
    var body: some View {
       
        NavigationView{
            List {
 
                ForEach(self.data.datas.filter{(self.search.isEmpty ? true : $0.title.localizedCaseInsensitiveContains(self.search))}, id: \.id) { rs in
                    
                    NavigationLink(destination: Detail(data: rs)) {
                        Text(rs.title)
                    }
                }
            }
            .navigationBarTitle("Search Movie")
            .searchable(text: self.$search)
            {
                ForEach(data.datas, id:\.id) { info in
                    HStack {
                        Text(info.title)
                            .searchCompletion(info.title)
                    }
                }
            }
        }
    }
}

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


struct Detail : View {
    
    var data : dataType
    
    var body : some View{
        VStack {
            Text(data.title)
                .font(.title)
                .fontWeight(.bold)
            Text(data.description)
        }.padding()
    }
}
Model.swift
 
//
//  Model.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//
import SwiftUI
import Firebase

class getData : ObservableObject{
    
    @Published var datas = [dataType]()
    
    init() {
        
        let db = Firestore.firestore()
        
        db.collection("movielist").getDocuments { (snap, err) in
            
            if err != nil{
                
                print((err?.localizedDescription)!)
                return
            }
            
            for i in snap!.documents{
                
                let id = i.documentID
                let title = i.get("title") as! String
                let description = i.get("description") as! String
                
                self.datas.append(dataType(id: id, title: title, description: description))
            }
        }
    }
}

struct dataType : Identifiable {
    
    var id : String
    var title : String
    var description : String
}
 
//
//  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 15, 2022

How to install laravel 9

How to install laravel 9

C:\xampp>cd htdocs
C:\xampp\htdocs>composer global require laravel/installer
C:\xampp\htdocs>cd laravel_9
C:\xampp\htdocs\laravel_9>laravel new blog
Installing laravel/laravel (v9.0.0)
Application ready! Build something amazing.
C:\xampp\htdocs\laravel_9>cd blog
C:\xampp\htdocs\laravel_9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Monday, February 14, 2022

SwiftUI Search Bar

SwiftUI Search Bar

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

import SwiftUI

struct ContentView: View {
    private var listOfCountry = countryList
    @State var searchText = ""
    
    var body: some View {
        NavigationView {
            List {
                ForEach(countries, id: \.self) { country in
                    HStack {
                        Text(country.capitalized)
                        Spacer()
                        Image(systemName: "paperplane")
                            .foregroundColor(Color.blue.opacity(0.8))
                    }
                    .padding()
                }
            }
            .searchable(text: $searchText)
            .navigationTitle("Countries")
        }
    }
    
    // Filter countries
    var countries: [String] {
        // Make countries lowercased
        let lcCountries = listOfCountry.map { $0.lowercased() }
        
        return searchText == "" ? lcCountries : lcCountries.filter { $0.contains(searchText.lowercased()) }
    }
}


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

import Foundation

public var countryList = [
    "Afghanistan",
    "Albania",
    "Algeria",
    "American Samoa",
    "Andorra",
    "Angola",
    "Anguilla",
    "Antarctica",
    "Antigua and Barbuda",
    "Argentina",
    "Armenia",
    "Aruba",
    "Australia",
    "Austria",
    "Azerbaijan",
    "Bahamas (the)",
    "Bahrain",
    "Bangladesh",
    "Barbados",
    "Belarus",
    "Belgium",
    "Belize",
    "Benin",
    "Bermuda",
    "Bhutan",
    "Bolivia (Plurinational State of)",
    "Bonaire, Sint Eustatius and Saba",
    "Bosnia and Herzegovina",
    "Botswana",
    "Bouvet Island",
    "Brazil",
    "British Indian Ocean Territory (the)",
    "Brunei Darussalam",
    "Bulgaria",
    "Burkina Faso",
    "Burundi",
    "Cabo Verde",
    "Cambodia",
    "Cameroon",
    "Canada",
    "Cayman Islands (the)",
    "Central African Republic (the)",
    "Chad",
    "Chile",
    "China",
    "Christmas Island",
    "Cocos (Keeling) Islands (the)",
    "Colombia",
    "Comoros (the)",
    "Congo (the Democratic Republic of the)",
    "Congo (the)",
    "Cook Islands (the)",
    "Costa Rica",
    "Croatia",
    "Cuba",
    "Curaรงao",
    "Cyprus",
    "Czechia",
    "Cรดte d'Ivoire",
    "Denmark",
    "Djibouti",
    "Dominica",
    "Dominican Republic (the)",
    "Ecuador",
    "Egypt",
    "El Salvador",
    "Equatorial Guinea",
    "Eritrea",
    "Estonia",
    "Eswatini",
    "Ethiopia",
    "Falkland Islands (the) [Malvinas]",
    "Faroe Islands (the)",
    "Fiji",
    "Finland",
    "France",
    "French Guiana",
    "French Polynesia",
    "French Southern Territories (the)",
    "Gabon",
    "Gambia (the)",
    "Georgia",
    "Germany",
    "Ghana",
    "Gibraltar",
    "Greece",
    "Greenland",
    "Grenada",
    "Guadeloupe",
    "Guam",
    "Guatemala",
    "Guernsey",
    "Guinea",
    "Guinea-Bissau",
    "Guyana",
    "Haiti",
    "Heard Island and McDonald Islands",
    "Holy See (the)",
    "Honduras",
    "Hong Kong",
    "Hungary",
    "Iceland",
    "India",
    "Indonesia",
    "Iran (Islamic Republic of)",
    "Iraq",
    "Ireland",
    "Isle of Man",
    "Israel",
    "Italy",
    "Jamaica",
    "Japan",
    "Jersey",
    "Jordan",
    "Kazakhstan",
    "Kenya",
    "Kiribati",
    "Korea (the Democratic People's Republic of)",
    "Korea (the Republic of)",
    "Kuwait",
    "Kyrgyzstan",
    "Lao People's Democratic Republic (the)",
    "Latvia",
    "Lebanon",
    "Lesotho",
    "Liberia",
    "Libya",
    "Liechtenstein",
    "Lithuania",
    "Luxembourg",
    "Macao",
    "Madagascar",
    "Malawi",
    "Malaysia",
    "Maldives",
    "Mali",
    "Malta",
    "Marshall Islands (the)",
    "Martinique",
    "Mauritania",
    "Mauritius",
    "Mayotte",
    "Mexico",
    "Micronesia (Federated States of)",
    "Moldova (the Republic of)",
    "Monaco",
    "Mongolia",
    "Montenegro",
    "Montserrat",
    "Morocco",
    "Mozambique",
    "Myanmar",
    "Namibia",
    "Nauru",
    "Nepal",
    "Netherlands (the)",
    "New Caledonia",
    "New Zealand",
    "Nicaragua",
    "Niger (the)",
    "Nigeria",
    "Niue",
    "Norfolk Island",
    "Northern Mariana Islands (the)",
    "Norway",
    "Oman",
    "Pakistan",
    "Palau",
    "Palestine, State of",
    "Panama",
    "Papua New Guinea",
    "Paraguay",
    "Peru",
    "Philippines (the)",
    "Pitcairn",
    "Poland",
    "Portugal",
    "Puerto Rico",
    "Qatar",
    "Republic of North Macedonia",
    "Romania",
    "Russian Federation (the)",
    "Rwanda",
    "Rรฉunion",
    "Saint Barthรฉlemy",
    "Saint Helena, Ascension and Tristan da Cunha",
    "Saint Kitts and Nevis",
    "Saint Lucia",
    "Saint Martin (French part)",
    "Saint Pierre and Miquelon",
    "Saint Vincent and the Grenadines",
    "Samoa",
    "San Marino",
    "Sao Tome and Principe",
    "Saudi Arabia",
    "Senegal",
    "Serbia",
    "Seychelles",
    "Sierra Leone",
    "Singapore",
    "Sint Maarten (Dutch part)",
    "Slovakia",
    "Slovenia",
    "Solomon Islands",
    "Somalia",
    "South Africa",
    "South Georgia and the South Sandwich Islands",
    "South Sudan",
    "Spain",
    "Sri Lanka",
    "Sudan (the)",
    "Suriname",
    "Svalbard and Jan Mayen",
    "Sweden",
    "Switzerland",
    "Syrian Arab Republic",
    "Taiwan",
    "Tajikistan",
    "Tanzania, United Republic of",
    "Thailand",
    "Timor-Leste",
    "Togo",
    "Tokelau",
    "Tonga",
    "Trinidad and Tobago",
    "Tunisia",
    "Turkey",
    "Turkmenistan",
    "Turks and Caicos Islands (the)",
    "Tuvalu",
    "Uganda",
    "Ukraine",
    "United Arab Emirates (the)",
    "United Kingdom of Great Britain and Northern Ireland (the)",
    "United States Minor Outlying Islands (the)",
    "United States of America (the)",
    "Uruguay",
    "Uzbekistan",
    "Vanuatu",
    "Venezuela (Bolivarian Republic of)",
    "Viet Nam",
    "Virgin Islands (British)",
    "Virgin Islands (U.S.)",
    "Wallis and Futuna",
    "Western Sahara",
    "Yemen",
    "Zambia",
    "Zimbabwe",
    "ร…land Islands"
]

React Native Login Screen - package

React Native Login Screen - package

https://www.npmjs.com/package/react-native-login-screen

install : npm i react-native-login-screen

Saturday, February 12, 2022

SwiftUI Login Screen

SwiftUI Login Screen

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

import SwiftUI

struct ContentView: View {
    @State private var username = ""
    @State private var password = ""
    @State private var wrongUsername: Float = 0
    @State private var wrongPassword: Float  = 0
    @State private var showingLoginScreen = false
    
    
    var body: some View {
        NavigationView {
            ZStack {
                Color.orange
                    .ignoresSafeArea()
                Circle()
                    .scale(1.9)
                    .foregroundColor(.white.opacity(0.29))
                Circle()
                    .scale(1.7)
                    .foregroundColor(.white)

                VStack {
                    Text("Login")
                        .font(.largeTitle)
                        .bold()
                        .padding()
                    
                    TextField("Username", text: $username)
                        .padding()
                        .frame(width: 300, height: 50)
                        .background(Color.black.opacity(0.05))
                        .cornerRadius(10)
                        .border(.red, width: CGFloat(wrongUsername))
                        
                    
                    SecureField("Password", text: $password)
                        .padding()
                        .frame(width: 300, height: 50)
                        .background(Color.black.opacity(0.05))
                        .cornerRadius(10)
                        .border(.red, width: CGFloat(wrongPassword))
                    
                    Button("Login") {
                        authenticateUser(username: username, password: password)
                        }
                    .foregroundColor(.white)
                    .frame(width: 300, height: 50)
                    .background(Color.orange)
                    .cornerRadius(10)
                    
                    NavigationLink(destination: Text("You are logged in @\(username)"), isActive: $showingLoginScreen) {
                        EmptyView()
                    }
                }
            }.navigationBarHidden(true)
        }
    }
    
    func authenticateUser(username: String, password: String) {
        if username.lowercased() == "cairocoders" {
            wrongUsername = 0
            if password.lowercased() == "123456" {
                wrongPassword = 0
                showingLoginScreen = true
            } else {
                wrongPassword = 2
            }
        } else {
            wrongUsername = 2
        }
    }
}


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

SwiftUI Pop Up Menu

SwiftUI Pop Up Menu

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

import SwiftUI

struct ContentView: View {
    var body: some View {
        Menu {
            Button("Cancel", role: .destructive) {
                print("Cancel")
            }
            
            Menu {
                Button(role: .destructive) {
                    print("Report")
                } label: {
                    Label("Report", systemImage: "flag.fill")
                }
            } label: {
                Label("Other", systemImage: "questionmark.circle")
            }
            
            Button {
                print("Download")
            } label: {
                Label("Download", systemImage: "tray.and.arrow.down.fill")
            }
            
            Button {
                print("Share")
            } label: {
                Label("Share", systemImage: "square.and.arrow.up")
            }
        } label: {
            Label("Settings", systemImage: "gearshape.fill")
        }
        
    }
}

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

How to Install React Native on Mac

How to Install React Native on Mac

Friday, February 11, 2022

Vue.js PHP Mysql Submit Form Data with Alert Message

Vue.js PHP Mysql Submit Form Data with Alert Message

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

Axios 
CDN : https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>Vue.js PHP Mysql Submit Form Data with Alert Message</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/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>
<div id="alert">

	<div class="topcorner alert_danger" v-if="isError">
		<span class="closebutton" @click="clearMessage();">×</span>
		<span class="glyphicon glyphicon-alert"></span> {{ responseMessage }}
	</div>
	<div class="topcorner alert_success" v-if="isSuccess">
		<span class="closebutton" @click="clearMessage();">×</span>
		<span class="glyphicon glyphicon-check-square-o"></span> {{ responseMessage }}
	</div>
	
	<div class="container">
		<h1 class="page-header text-center">Vue.js PHP Mysql Submit Form Data with Alert Message</h1>
		<div class="col-md-4">
			<div class="form-group">
				<label>First Name:</label>
				<input type="text" class="form-control" v-model="newMember.firstname" v-on:keyup="keymonitor">
			</div>
			<div class="form-group">
				<label>Last Name:</label>
				<input type="text" class="form-control" v-model="newMember.lastname" v-on:keyup="keymonitor">
			</div>
			<button class="btn btn-primary" @click="insertMember();"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button> <button class="btn btn-danger" @click="clearForm();"><span class="glyphicon glyphicon-refresh"></span> Clear</button>
		</div>
		<div class="col-md-8">
			<table class="table table-bordered table-striped">
				<thead>
					<th>Member ID</th>
					<th>First Name</th>
					<th>Last Name</th>
				</thead>
				<tbody>
					<tr v-for="member in members">
						<td>{{ member.id }}</td>
						<td>{{ member.firstname }}</td>
						<td>{{ member.lastname }}</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="app.js"></script>
<style type="text/css">
		.topcorner{
			position:absolute;
			top:5px;
			right:5px;
		}
		.alert_danger {
		    padding: 15px;
		    background-color: #f44336;
		    color: white;
		}

		.alert_success {
		    padding: 15px;
		    background-color: #4CAF50;
		    color: white;
		}

		.closebutton {
		    margin-left: 15px;
		    color: white;
		    font-weight: bold;
		    float: right;
		    font-size: 22px;
		    line-height: 20px;
		    cursor: pointer;
		    transition: 0.3s;
		}

		.closebutton:hover {
		    color: black;
		}
</style>
</body>
</html>
app.js
//app.js
var app = new Vue({
	el: '#alert',
	data:{
		newMember: {firstname: '', lastname: ''},
		alertMessage: false,
		isSuccess: false,
		isError: false,
		responseMessage: "",
		members: []
	},

	mounted: function(){
		this.fetchMembers();
	},

	methods:{
		keymonitor: function(event) {
       		if(event.key == "Enter"){
         		app.insertMember();
        	}
       	},

       	fetchMembers: function(){
			axios.post('action.php')
				.then(function(response){
					app.members = response.data.members;
				});
       	},

		insertMember: function(){
			var memberForm = app.toFormData(app.newMember);
			axios.post('action.php?action=add', memberForm)
				.then(function(response){
					console.log(response);
					if(response.data.error){
						app.alertMessage = true;
						app.isError = true;
						app.isSuccess = false;
						app.responseMessage = response.data.message;
						setTimeout(function(){
							app.clearMessage();
						},3000);
					}
					else{
						app.isSuccess = true;
						app.isError = false;
						app.alertMessage = true;
						app.responseMessage = response.data.message;
						app.newMember = {firstname: '', lastname:''};
						app.fetchMembers();
						setTimeout(function(){
							app.clearMessage();
						},3000);
					}
				});
		},

		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.isError = false;
			app.isSuccess = false;
		},

		clearForm: function(){
			app.newMember=app.newMember = {firstname: '', lastname:''};
		}



	}
});
action.php
//action.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

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

$action="show";

if(isset($_GET['action'])){
	$action=$_GET['action'];
}

if($action=='show'){
	$sql = "select * from members";
	$query = $conn->query($sql);
	$members = array();

	while($row = $query->fetch_array()){
		array_push($members, $row);
	}

	$out['members'] = $members;
}

if($action=='add'){
	$firstname=$_POST['firstname'];
	$lastname=$_POST['lastname'];

	if($firstname==''){
		$out['error']=true;
		$out['message']='Add Member Failed. Username Empty.';
	}
	elseif($lastname==''){
		$out['error']=true;
		$out['message']='Add Member Failed. lastname Empty.';
	}
	else{
		$sql="insert into members (	firstname, lastname) values ('$firstname', '$lastname')";
		$query=$conn->query($sql);

		if($query){
			$out['message']='Member Successfully Added';
		}
		else{
			$out['error']=true;
			$out['message']='Error in Adding Occured';
		}
		
	}
}




$conn->close();

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

?>

SwiftUI WebView

SwiftUI WebView

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

import SwiftUI
import WebKit

struct ContentView: View {
    @State private var showWebView = false
    private let urlString: String = "https://www.apple.com/"
    
    var body: some View {
        VStack(spacing: 10) {

            WebView(url: URL(string: urlString)!).frame(height: 650.0)
                .cornerRadius(10)
                .shadow(color: .black.opacity(0.3), radius: 20.0, x: 5, y: 5)
                
            
            // link that opens in a new window
            Link(destination: URL(string: urlString)!, label: {
                Text("Open in new window")
                    .foregroundColor(.blue)
            })
            
            // Present WebView as a Bottom Sheet
            Button {
                showWebView.toggle()
            } label: {
                Text("Open in a sheet")
            }
            .sheet(isPresented: $showWebView) {
                WebView(url: URL(string: urlString)!)
            }
            Spacer()
            
        }.padding()
    }
}

struct WebView: UIViewRepresentable {
    
    var url: URL
    
    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }
    
    func updateUIView(_ webView: WKWebView, context: Context) {
        let request = URLRequest(url: url)
        webView.load(request)
    }
}

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

SwiftUI Password Strength Checker

SwiftUI Password Strength Checker

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

import SwiftUI

struct ContentView: View {
    
    @State var email : String = ""
    @State var password : String = ""
    @State var passwordStrength : Int = 0
    
    func checkStrength(_ password: String) -> Int {
        let passwordLength = password.count
        var containsSymbol = false
        var containsUppercase = false

        for character in password {
            if "ABCDEFGHIJKLMNOPQRSTUVWXYZ".contains(character) {
                containsUppercase = true
            }
            
            if "!£$%&/()=?^;:_รง°§*,.-_".contains(character) {
                containsSymbol = true
            }
        }
        
        if passwordLength > 8 && containsSymbol && containsUppercase {
            return 1
        } else {
            return 0
        }
    }
    
    var body: some View {
        VStack {
            Spacer()
            
            Group {
                TextField("Email", text: $email)
                    .keyboardType(.emailAddress)
                    .autocapitalization(.none)
                TextField("Password", text: $password)
            }
            .padding(16)
            .background(Color.white)
            
            HStack {
                if checkStrength(password) == 0  {
                    Text("Weak").foregroundColor(Color.red)
                        .font(.system(size: 30.0)).padding()
                } else {
                    Text("Strong").foregroundColor(Color.green)
                        .font(.system(size: 30.0)).padding()
                }
            }
            
            Button {

            } label: {
                HStack {
                    Spacer()
                    Text("Log In")
                        .foregroundColor(.white)
                        .padding(.vertical, 10)
                        .font(.system(size: 14, weight: .semibold))
                    Spacer()
                }.background(Color.blue)
                
            }
            
            Spacer()
            
        }.padding()
        .background(SwiftUI.Color.gray.edgesIgnoringSafeArea(.all))
    }
}

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

Related Post