article

Saturday, October 30, 2021

ReactJS Image gallery - React Masonry Component

ReactJS Image gallery - React Masonry Component

In this tutorial we'll create a responsice image gallery like pinterest with react-masonry-component


Install react-masonry-component

https://github.com/eiriklv/react-masonry-component

npm i react-masonry-component

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

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

// Dome dummy content
const PHOTOS = [
  {
    imageUrl:
      "https://images.pexels.com/photos/1076240/pexels-photo-1076240.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/757444/pexels-photo-757444.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/2516406/pexels-photo-2516406.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/2413238/pexels-photo-2413238.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/1714455/pexels-photo-1714455.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/2407265/pexels-photo-2407265.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/3698534/pexels-photo-3698534.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/2467670/pexels-photo-2467670.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/2623690/pexels-photo-2623690.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/3047993/pexels-photo-3047993.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/239546/pexels-photo-239546.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/4496891/pexels-photo-4496891.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
  {
    imageUrl:
      "https://images.pexels.com/photos/8979525/pexels-photo-8979525.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
  },
];

// Masory Options
const masonryOptions = {
  fitWidth: false,
  columnWidth: 300,
  gutter: 30,
  itemSelector: ".photo-item",
};

const App = () => {
  return (
    <div> <h1>ReactJS Image gallery - React Masonry Component</h1>
      <Masony
        className={"photo-list"}
        elementType={"ul"}
        options={masonryOptions}
        disableImagesLoaded={false}
        updateOnEachImageLoad={false}
      >
        {PHOTOS.map((photo) => (
          <li className={`photo-item`}>
            <img src={photo.imageUrl} alt="" />
          </li>
        ))}
      </Masony>
    </div>
  );
};

export default App;
src/App.css
//src/App.css
.photo-list {
    width: 90%;
    list-style: none;
    margin: 20px auto;
}

.photo-item {
    display: flex;
    width: 300px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, .12);
    margin: 20px 0;
}

.photo-item img {
    display: flex;
    width: 100%;
    border: 4px double rgba(0, 0, 0, .12);
}

ReactJS pie charts

ReactJS pie charts

Install victory-pie

npm install victory-pie --save
src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

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

const myData = [
  { x: "PHP", y: 900 },
  { x: "Python", y: 400 },
  { x: "Javascript", y: 300 },
];

const App = () => {
  return (
    <div style={{ height: 620 }}>
      <VictoryPie
        data={myData}
        colorScale={["blue", "yellow", "red"]}
        radius={100}
      />
    </div>
  );
};

export default App;

Next.js How to call API and display records in table

Next.js How to call API and display records in table

Install axios

https://www.npmjs.com/package/axios

npm i axios

C:\nextjs>npm i axios
C:\nextjs>npm run dev

getInitialProps method to call the API.
getInitialProps method will be called at both server and client side.

pages/index.js
//pages/index.js
import axios from "axios"; //npm i axios

const Index = ({ userList }) => <div style={{ margin: 20 }}>
  <h3>Next.js How to call API and display records in table</h3>
  <table border="1">
    <thead>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>Avatar</th>
    </thead>
    <tbody>
      {userList.data.map((x, i) => <tr key={i}>
        <td>{x.first_name}</td>
        <td>{x.last_name}</td>
        <td>{x.email}</td>
        <td><img src={x.avatar} width="50" height="50" /></td>
      </tr>)}
    </tbody>
  </table>
</div>
 
Index.getInitialProps = async () => {
  const { data } = await axios.get('https://reqres.in/api/users');
  return { userList: data };
}
 
export default Index;

Next.js Simple Shared components

Next.js Simple Shared components

Shared components is to organize pages together.

components/Layout.js
//components/Layout.js
import Link from "next/link";
import Head from "next/head";
 
const Layout = ({ children, title }) => {
  return <div className="p-3">
    <Head>
      <title>{title} - Cairocoders</title>
    </Head>
    <h3>Next.js Simple Shared components </h3>
    <br />
 
    <Link href="/">
      <a style={{ marginRight: 15 }}>Home</a>
    </Link>
    <Link href="/about">
      <a style={{ marginRight: 15 }}>About</a>
    </Link>
    <Link href="/contact">
      <a>Contact</a>
    </Link>
 
    <h1>{title}</h1>
    {children}
 
    <div style={{ marginTop: 30 }}>
      © {new Date().getFullYear()}
    </div>
  </div>
}
 
export default Layout;
pages/index.js
//pages/index.js
import Layout from "../components/Layout";
 
const Index = () => <Layout title="Home">
  <p>Welcome to the Home page!</p>
</Layout>
 
export default Index;
pages/about.js
//pages/about.js
import Layout from "../components/Layout";
 
const About = () => <Layout title="About">
  <p>This is About page!</p>
</Layout>
 
export default About;
pages/contact.js
//pages/contact.js
import Layout from "../components/Layout";
 
const Contact = () => <Layout title="Contact">
  <p>This is Contact page!</p>
</Layout>
 
export default Contact;

Next.js Simple Navigation Page to Page using Link

Next.js Simple Navigation Page to Page using Link

pages/index.js
//pages/index.js
import Link from "next/link";
 
const Index = () => <div>
 
  <h3>Next.js Simple Navigate page to page using link </h3>
  <br />
 
  <Link href="/">
    <a style={{ marginRight: 15 }}>Home</a>
  </Link>
  <Link href="/about">
    <a style={{ marginRight: 15 }}>About</a>
  </Link>
  <Link href="/contact">
    <a>Contact</a>
  </Link>
 
  <h1>Home page!</h1>
</div>
 
export default Index;
pages/about.js
//pages/about.js
import Link from "next/link";
 
const About = () => <div>
 
  <h3>Next.js Simple Navigate page to page using link </h3>
  <br />
 
  <Link href="/">
    <a style={{ marginRight: 15 }}>Home</a>
  </Link>
  <Link href="/about">
    <a style={{ marginRight: 15 }}>About</a>
  </Link>
  <Link href="/contact">
    <a>Contact</a>
  </Link>
 
  <h1>About page!</h1>
</div>
 
export default About;
pages/contact.js
//pages/contact.js
import Link from "next/link";
 
const Contact = () => <div>
 
  <h3>Next.js Simple Navigate page to page using link </h3>
  <br />
 
  <Link href="/">
    <a style={{ marginRight: 15 }}>Home</a>
  </Link>
  <Link href="/about">
    <a style={{ marginRight: 15 }}>About</a>
  </Link>
  <Link href="/contact">
    <a>Contact</a>
  </Link>
 
  <h1>Contact page!</h1>
</div>
 
export default Contact;

Friday, October 29, 2021

ReactJS Axios PHP Mysql Form Validation with Formik and Yup

ReactJS Axios PHP Mysql Form Validation with Formik and Yup

In this tutorial, I will show you how to implement React Form Validation with Formik, Yup, axios and bootstap also after validated the form by submiting the form the data will save to database using mysql and php

Formik : https://formik.org/
Yup : https://www.npmjs.com/package/yup
Bootstrap : https://react-bootstrap.github.io/getting-started/introduction/
Axios : https://github.com/axios/axios

Install Formik
npm install formik yup
C:\reactdev\myreactdev>npm install formik yup

https://github.com/axios/axios

Installing the Axios Client
$ npm install axios

C:\reactdev\myreactdev>npm install axios

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

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

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

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

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

class App extends React.Component {
    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(data) {
        console.log(JSON.stringify(data, null, 2));

        let formData = new FormData();
        formData.append('fullname', data.fullname)
        formData.append('username', data.username)
        formData.append('email', data.email)
        formData.append('password', data.password)

        axios({
            method: 'post',
            url: 'http://localhost/devtest/reactjs/reg.php/',
            data: formData,
            config: { headers: {'Content-Type': 'multipart/form-data' }}
        })
        .then(function (response) {
            //handle success
            console.log(response)
            alert('New User Successfully Added.');  
        })
        .catch(function (response) {
            //handle error
            console.log(response)
        });
    }

    validationSchema() {
        return Yup.object().shape({
          fullname: Yup.string().required('Fullname is required'),
          username: Yup.string()
            .required('Username is required')
            .min(6, 'Username must be at least 6 characters')
            .max(20, 'Username must not exceed 20 characters'),
          email: Yup.string()
            .required('Email is required')
            .email('Email is invalid'),
          password: Yup.string()
            .required('Password is required')
            .min(6, 'Password must be at least 6 characters')
            .max(40, 'Password must not exceed 40 characters'),
          confirmPassword: Yup.string()
            .required('Confirm Password is required')
            .oneOf([Yup.ref('password'), null], 'Confirm Password does not match'),
          acceptTerms: Yup.bool().oneOf([true], 'Accept Terms is required'),
        });
    }

    render() {
        const initialValues = {
            fullname: '',
            username: '',
            email: '',
            password: '',
            confirmPassword: '',
            acceptTerms: false,
        };

        return (
            <div className="container" style={{padding: 20}}>
            <div className="register-form"><h1>ReactJS Axios PHP Mysql Form Validation with Formik and Yup</h1>
              <Formik
                initialValues={initialValues}
                validationSchema={this.validationSchema}
                onSubmit={this.handleSubmit}>

                {({ resetForm }) => (
                  <Form>
                    <div className="form-group">
                      <label>Full Name</label>
                      <Field name="fullname" type="text" className="form-control"/>
                      <ErrorMessage name="fullname" component="div" className="text-danger"/>
                    </div>
      
                    <div className="form-group">
                      <label htmlFor="username"> Username </label>
                      <Field name="username" type="text" className="form-control" />
                      <ErrorMessage name="username" component="div" className="text-danger"/>
                    </div>
      
                    <div className="form-group">
                      <label htmlFor="email"> Email </label>
                      <Field name="email" type="email" className="form-control" />
                      <ErrorMessage name="email" component="div" className="text-danger"/>
                    </div>
      
                    <div className="form-group">
                      <label htmlFor="password"> Password </label>
                      <Field name="password" type="password" className="form-control"/>
                      <ErrorMessage name="password" component="div" className="text-danger"/>
                    </div>
      
                    <div className="form-group">
                      <label htmlFor="confirmPassword"> Confirm Password </label>
                      <Field name="confirmPassword" type="password" className="form-control"/>
                      <ErrorMessage name="confirmPassword" component="div" className="text-danger"/>
                    </div>
      
                    <div className="form-group form-check"><br/>
                      <Field name="acceptTerms" type="checkbox" className="form-check-input"/>
                      <label htmlFor="acceptTerms" className="form-check-label">
                        I have read and agree to the Terms
                      </label>
                      <ErrorMessage name="acceptTerms" component="div" className="text-danger"/>
                    </div>
      
                    <div className="form-group">
                      <button type="submit" className="btn btn-primary">
                        Register
                      </button> 
                      <button type="button" onClick={resetForm} className="btn btn-warning">
                        Reset
                      </button>
                    </div>
                  </Form>
                )}
              </Formik>
            </div>
            </div>
        );
    }
}      
export default App;
http://localhost/devtest/reactjs/reg.php
//http://localhost/devtest/reactjs/reg.php
<?php
header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 

$con = mysqli_connect($host, $user, $password,$dbname);

$method = $_SERVER['REQUEST_METHOD'];


if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
	case 'POST':	
		$fullname = $_POST["fullname"];
		$username = $_POST["username"];
		$email = $_POST["email"];
		$password = $_POST["password"];
		$sql = "insert into tbl_user (fullname, username, email, password) values ('$fullname', '$username', '$email', '$password')"; 
	break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'POST') {
    echo json_encode($result);
} else {
    echo mysqli_affected_rows($con);
}

$con->close();

SwiftUI Display Badge Value

SwiftUI Display Badge Value

ContentView.swift
 
//
//  ContentView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @EnvironmentObject var order: Order
    private var badgePosition: CGFloat = 2
    private var tabsCount: CGFloat = 3
    
    var body: some View {
        GeometryReader { geometry in
            ZStack(alignment: .bottomLeading) {
            // TabView
            TabView {
              MenuView()
                .tabItem {
                  Image(systemName: "list.dash")
                  Text("Menu")
              }.tag(0)

              OrderView()
                .tabItem {
                  Image(systemName: "cart")
                  Text("Order")
              }.tag(1)

              Text("Favourite")
                .tabItem {
                  Image(systemName: "star")
                  Text("Favourite")
              }.tag(2)
            }

            // Badge View
            ZStack {
              Circle()
                .foregroundColor(.red)

                Text("\(self.order.items.count)")
                .foregroundColor(.white)
                .font(Font.system(size: 12))
            }
            .frame(width: 15, height: 15)
            .offset(x: ( ( 2 * self.badgePosition) - 0.95 ) * ( geometry.size.width / ( 2 * self.tabsCount ) ) + 2, y: -25)
            .opacity(self.order.items.count == 0 ? 0 : 1.0)
          }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static let order = Order()
    static var previews: some View {
        ContentView().environmentObject(order)
    }
}
MenuView.swift
 
//
//  MenuView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct MenuView: View {
    
    @EnvironmentObject var order: Order
    
    var body: some View {
        VStack {
            Button(action:{
                self.order.add(item: "Order Item")
            }) {
                Image(systemName: "cart.badge.plus")
                Text("Add to cart")
            }.padding(.bottom, 30.0)
            Button(action:{
                self.order.remove(item: "Order Item")
            }) {
                Image(systemName: "cart.badge.minus")
                Text("Remove from cart")
            }
        }
    }
    
}

struct MenuView_Previews: PreviewProvider {
    static let order = Order()
    static var previews: some View {
        MenuView().environmentObject(order)
    }
}
OrderView.swift
 
//
//  OrderView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct OrderView: View {
    
    @EnvironmentObject var order: Order
    
    
    var body: some View {
        List {
            ForEach(order.items, id: \.self) { item in
                Text(item)
            }
        }
    }
}

struct OrderView_Previews: PreviewProvider {
    static let order = Order()
    static var previews: some View {
        OrderView().environmentObject(order)
    }
}
Order.swift
 
//
//  Order.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

class Order: ObservableObject {
    
    @Published var items = [String]()

    func add(item: String) {
        items.append(item)
        print(items)
    }

    func remove(item: String) {
        if let index = items.firstIndex(of: item) {
            items.remove(at: index)
            print(items)
        }
    }
}
SwiftuitestApp.swift
 
//
//  SwiftuitestApp.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

@main
struct SwiftuitestApp: App {
    @StateObject private var order = Order()
    var body: some Scene {
        WindowGroup {
            ContentView().environmentObject(order)
        }
    }
}

Thursday, October 28, 2021

SwiftUI Custom Tab Bar

SwiftUI Custom Tab Bar

ContentView.swift
 
//
//  ContentView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
     
    @State var index = 0
    
    var body: some View {
        VStack {
            
            ZStack {
                if self.index == 0 {
                    Color.green.edgesIgnoringSafeArea(.top)
                    VStack {
                        Text("Home").foregroundColor(Color.white)
                        Image(systemName: "house.fill")
                            .resizable()
                            .frame(width: 200, height: 200)
                    }
                }
                else if self.index == 1 {
                    Color.blue.edgesIgnoringSafeArea(.top)
                    VStack {
                        Text("Profile").foregroundColor(Color.white)
                        Image(systemName: "person.fill")
                            .resizable()
                            .frame(width: 200, height: 200)
                    }
                }
                else if self.index == 2 {
                    Color.red.edgesIgnoringSafeArea(.top)
                    VStack {
                        Text("Notification").foregroundColor(Color.white)
                        Image(systemName: "bell.fill")
                            .resizable()
                            .frame(width: 200, height: 200)
                    }
                }
                else{
                    Color.yellow.edgesIgnoringSafeArea(.top)
                    VStack {
                        Text("Cart").foregroundColor(Color.white)
                        Image(systemName: "cart.fill")
                            .resizable()
                            .frame(width: 200, height: 200)
                    }
                }
            }
                
            CustomTabBar(index: $index)
        }.animation(.spring())
    }
}

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

import SwiftUI

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

struct CustomTabBar_Previews: PreviewProvider {
    @State static var index = 0
    static var previews: some View {
        CustomTabBar(index: $index)
    }
}

Wednesday, October 27, 2021

ReactJS Axios PHP Mysql CRUD (Create Read Update and Delete)

ReactJS Axios PHP Mysql CRUD (Create Read Update and Delete)

https://github.com/axios/axios

The componentDidMount() life-cycle hook. This is executed when your React component is inserted/mounted in the DOM.

Installing the Axios Client
$ npm install axios

C:\reactdev\myreactdev>npm install axios

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

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

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

header("Access-Control-Allow-Origin: *"); add this CORS header to enable any domain to send HTTP requests to these endpoints:

CREATE TABLE `contacts` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(150) NOT NULL,
  `city` varchar(150) NOT NULL,
  `country` varchar(150) NOT NULL,
  `job` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `contacts` (`id`, `name`, `email`, `city`, `country`, `job`) VALUES
(36, 'Cara Stevens', 'cairocoders@gmail.com', 'Olongapo City', 'Phil', 'coders'),
(37, 'Airi Satou', 'AiriSatou@gmail.com', 'Tokyo', 'Japan', 'Accountant'),
(38, 'Angelica Ramos', 'AngelicaRamos@gmail.com', 'London', 'United Kingdom', 'Chief Executive Officer'),
(39, 'Ashton Cox', 'AshtonCox@gmail.com', 'San Francisco', 'USA', 'Junior Technical Author');

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

ALTER TABLE `contacts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=40;


src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'
 
ReactDOM.render(
  <App />,
  document.getElementById('root')
)
src/App.js
//src/App.js
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Contact from './components/contact';
import Update from './components/update';
import Create from './components/create';

class App extends React.Component {
    render() {
        return (
            <Router>
            <div>
                <Route exact path='/' component={Contact} />
                  <Route path='/update/:id' component={Update} />
                <Route path='/create' component={Create} /> 
            </div>
            </Router>
        );
    }
}
export default App;
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/contact.js
//src/contact.js
import React from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

class Contact extends React.Component {
	constructor(props) {
		super(props);
		this.state = {contacts: []};
		this.headers = [
			{ key: 'id', label: 'Id'},
			{ key: 'name', label: 'Name' },
			{ key: 'email', label: 'Email' },
			{ key: 'country', label: 'Country' },
			{ key: 'city', label: 'City' },
			{ key: 'job', label: 'Job' }
			];
		this.deleteContact = this.deleteContact.bind(this);
	}
  componentDidMount() {
    const url = 'http://localhost/devtest/reactjs/contacts.php/'
    axios.get(url).then(response => response.data)
    .then((data) => {
      this.setState({ contacts: data })
      console.log(this.state.contacts)
     })
  }
	
  deleteContact(id, event) { //alert(id)
	event.preventDefault();
	if(window.confirm("Are you sure want to delete?")) {
		axios({
			method: 'post',
			url: 'http://localhost/devtest/reactjs/contacts.php/?delete=' + id
		})
		.then(function (response) {
			//handle success
			console.log(response)
			if(response.status === 200) {
				alert("Website deleted successfully");
			}
		})
		.catch(function (response) {
			//handle error
			console.log(response)
		});
    }
  }    
	
	render() {
		return (
			<div className="container"><h1>ReactJS Axios PHP Mysql CRUD (Create Read Update and Delete) </h1>
			<p><Link to="/create" className="btn btn-primary btn-xs">Add New Contact</Link> </p>
        	<table className="table table-bordered table-striped">
					<thead>
						<tr>
						{
							this.headers.map(function(h) {
								return (
									<th key = {h.key}>{h.label}</th>
								)
							})
						}
						  <th>Actions</th>
						</tr>
					</thead>
					<tbody>
						{
							this.state.contacts.map(function(item, key) {
							return (
								<tr key = {key}>
								  <td>{item.id}</td>
								  <td>{item.name}</td>
								  <td>{item.email}</td>
                  	<td>{item.country}</td>
                  	<td>{item.city}</td>
                  	<td>{item.job}</td>
								  <td>
                    <Link to={`/update/${item.id}`} className="btn btn-primary btn-xs">Edit</Link>
                      
					<Link to="#" onClick={this.deleteContact.bind(this, item.id)} className="btn btn-danger btn-xs">Delete</Link>
								  </td>
								</tr>)
							}.bind(this))
						}
					</tbody>
				</table>
			</div>
		)
	}
}

export default Contact;
src/update.js
//src/update.js
import React from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

class Update extends React.Component {
  constructor(props) {
    super(props);
    this.state = {id: '', name: '', email: '', city:'', country:'', job:''};
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
    axios.get('http://localhost/devtest/reactjs/contacts.php/?id=' + this.props.match.params.id)
    .then(response => response.data)
    .then((data) => {
      // handle success
      console.log(data);
      this.setState({ id: data.id, name: data.name, email: data.email, city: data.city, country: data.country, job: data.job })
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
    .then(function () {
      // always executed
    });
    
  }

  handleChange(event) {
	  const state = this.state
	  state[event.target.name] = event.target.value
	  this.setState(state);
  }

  handleSubmit(event) {
	  event.preventDefault();

      let formData = new FormData();
      formData.append('name', this.state.name)
      formData.append('email', this.state.email)
      formData.append('city', this.state.city)
      formData.append('country', this.state.country)
      formData.append('job', this.state.job)

      axios({
          method: 'post',
          url: 'http://localhost/devtest/reactjs/contacts.php/?id=' + this.props.match.params.id,
          data: formData,
          config: { headers: {'Content-Type': 'multipart/form-data' }}
      })
      .then(function (response) {
          //handle success
          console.log(response)
          if(response.status === 200) {
            alert("Contact update successfully.");
          }
      })
      .catch(function (response) {
          //handle error
          console.log(response)
      });
  }

  render() {
    return (
			<div className="container">
        <h1 className="page-header text-center">Update Contact</h1>
			  <Link to="/" className="btn btn-primary btn-xs">Home</Link>
        <div className="col-md-12">
            <div className="panel panel-primary">
                <div className="panel-body">
                <form onSubmit={this.handleSubmit}>
                <input type="hidden" name="id" value={this.state.id}/>
                <label>Name</label>
                <input type="text" name="name" className="form-control" value={this.state.name} onChange={this.handleChange} />
 
                <label>Email</label>
                <input type="email" name="email" className="form-control" value={this.state.email} onChange={this.handleChange} />
 
                <label>Country</label>
                <input type="text" name="country" className="form-control" value={this.state.country} onChange={this.handleChange} />
 
                <label>City</label>
                <input type="text" name="city" className="form-control" value={this.state.city} onChange={this.handleChange} />
 
                <label>Job</label>
                <input type="text" name="job" className="form-control" value={this.state.job} onChange={this.handleChange} />
                <br/>
                <input type="submit" className="btn btn-primary btn-block" value="Update Contact" />
            </form>
                </div>
            </div>
        	</div>
			   </div>
    );
  }
}

export default Update;
src/create.js
//src/create.js
import React from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

class Create extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: '', email:'', city:'', country:'', job:''};
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
	  const state = this.state
	  state[event.target.name] = event.target.value
	  this.setState(state);
  }
  handleSubmit(event) {
	event.preventDefault();

	let formData = new FormData();
	formData.append('name', this.state.name)
	formData.append('email', this.state.email)
	formData.append('city', this.state.city)
	formData.append('country', this.state.country)
	formData.append('job', this.state.job)

	axios({
		method: 'post',
		url: 'http://localhost/devtest/reactjs/contacts.php/',
		data: formData,
		config: { headers: {'Content-Type': 'multipart/form-data' }}
	})
	.then(function (response) {
		//handle success
		console.log(response)
		alert('New Contact Successfully Added.');  
	})
	.catch(function (response) {
		//handle error
		console.log(response)
	});

  }	
  render() {
    return (
		<div className="container">
        	<h1 className="page-header text-center">Add New Contact</h1>
		  	<Link to="/" className="btn btn-primary btn-xs">Home</Link>
			<div className="col-md-12">
            <div className="panel panel-primary">
                <div className="panel-body">
                <form onSubmit={this.handleSubmit}>
                <label>Name</label>
                <input type="text" name="name" className="form-control" value={this.state.name} onChange={this.handleChange} />
 
                <label>Email</label>
                <input type="email" name="email" className="form-control" value={this.state.email} onChange={this.handleChange} />
 
                <label>Country</label>
                <input type="text" name="country" className="form-control" value={this.state.country} onChange={this.handleChange} />
 
                <label>City</label>
                <input type="text" name="city" className="form-control" value={this.state.city} onChange={this.handleChange} />
 
                <label>Job</label>
                <input type="text" name="job" className="form-control" value={this.state.job} onChange={this.handleChange} />
                <br/>
                <input type="submit" className="btn btn-primary btn-block" value="Create Contact" />
            </form>
                </div>
            </div>
        	</div>
		</div>
    );
  }
}

export default Create;
http://localhost/devtest/reactjs/contacts.php
//http://localhost/devtest/reactjs/contacts.php
<?php
header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 
$id = '';

$con = mysqli_connect($host, $user, $password,$dbname);

$method = $_SERVER['REQUEST_METHOD'];


if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
    case 'GET':
	  if(isset($_GET["id"])){
		$id = $_GET['id'];  
	  }	  	
	  $sql = "select * from contacts".($id?" where id=$id":''); 
      break;
    case 'POST':
		if(isset($_GET["id"])){
			$id = $_GET['id'];  
			$name = $_POST["name"];
			$email = $_POST["email"];
			$country = $_POST["country"];
			$city = $_POST["city"];
			$job = $_POST["job"];
			$sql = "UPDATE contacts SET name='$name', email='$email', city='$city', country='$country', job='$job' WHERE id = $id"; 
		}else if(isset($_GET["delete"])){
			$delete = $_GET['delete'];  
			$sql = "DELETE FROM contacts WHERE id = $delete"; 
		}else{	
		  $name = $_POST["name"];
		  $email = $_POST["email"];
		  $country = $_POST["country"];
		  $city = $_POST["city"];
		  $job = $_POST["job"];

		  $sql = "insert into contacts (name, email, city, country, job) values ('$name', '$email', '$city', '$country', '$job')"; 
		}
	  break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'GET') {
    if (!$id) echo '[';
      for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
        echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
      }
    if (!$id) echo ']';
} elseif ($method == 'POST') {
    echo json_encode($result);
} else {
    echo mysqli_affected_rows($con);
}

$con->close();

Tuesday, October 26, 2021

SwiftUI Perform Network Requests to load json data from URL

SwiftUI Perform Network Requests to load json data from URL

Json : https://picsum.photos/v2/list

ContentView.swift
 
//
//  ContentView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @ObservedObject var items = Remote(url: URL(string: "https://picsum.photos/v2/list")!, transform: {
        try? JSONDecoder().decode([Photo].self, from: $0)
    })
    
    var body: some View {
        
        NavigationView {
            if items.value == nil {
                ProgressView()
                    .onAppear {
                        items.load()
                    }
            }else {
                List {
                    ForEach(items.value!) { photo in
                        NavigationLink(
                            destination:
                                PhotoView(photo.download_url),
                            label: {
                                Text(photo.author)
                            })
                    }
                }.navigationTitle("Authors")
            }
        }
    }
}

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

import Foundation

struct Photo: Codable, Identifiable {
    let id: String
    let author: String
    let width, height: Int
    let url, download_url: URL
}

struct PhotoLoadingError: Error {}
//View Model
final class Remote<Asc>: ObservableObject {
    @Published var result: Result<Asc, Error>? = nil
    var value: Asc? { try? result?.get()}
    let url:URL
    let transform: (Data) ->Asc?
    
    init(url: URL, transform: @escaping (Data) ->Asc?) {
        self.url = url
        self.transform = transform
    }
    
    func load() {
        URLSession.shared.dataTask(with: url) { (data, _, _) in
            DispatchQueue.main.async {
                if let d = data, let v = self.transform(d) {
                    self.result = .success(v)
                } else {
                    self.result = .failure(PhotoLoadingError())
                }
            }
        }.resume()
    }
}
PhotoView.swift
 
//
//  PhotoView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct PhotoView: View {
    @ObservedObject var image: Remote<UIImage>
    
    init(_ url: URL) {
        self.image = Remote(url: url, transform: {
            UIImage(data: $0)
        })
    }
    
    var body: some View {
        
        Group {
            if image.value == nil {
                ProgressView()
                    .onAppear { image.load() }
            } else {
                Image(uiImage: image.value!)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
            }
        }
    }
}

REST API CRUD (Create, Read, Update and Delete) Using PHP Class and PDO Mysql

REST API CRUD (Create, Read, Update and Delete) Using PHP Class and PDO Mysql

In this tutorial I'm going to show how to create a REST API CRUD Crate read update and delete using PHP Class and PDO Mysql

HTTP methods 

HTTP GET: Get/List/Retrieve an individual resource or a collection of resources.
HTTP POST: Create a new resource or resources.
HTTP PUT: Update an existing resource or collection of resources.
HTTP DELETE: Delete a resource or collection of resources.

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


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


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

ALTER TABLE `tbluser`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

Testing Rest API

Install the Advanced Rest Client
1. Go to Google Chrome's Web Store
2. Search for "Advanced Rest Client" https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo and Install the extension

DB.php
//DB.php
<?php
class Db {

    private $host = "localhost";
    private $db_name = "testingdb";
    private $username = "root";
    private $password = "";
    public $conn;

    // get the database connection
    public function getConnection() {
        $this->conn = null;

        try {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->exec("set names utf8");
        } catch (PDOException $exception) {
            echo "Database connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }

}
?>
User.php
//User.php
<?php
class User {

    // database connection and table name
    private $conn;
    private $table_name = "tbluser";
    // object properties
    public $id;
    public $name;
    public $username;

    // constructor with $db as database connection
    public function __construct($db) {
        $this->conn = $db;
    }
	
	// read user
    function read() {
        // query to select all
        $query = "SELECT *
            FROM
                " . $this->table_name . "
            ORDER BY
                id";
        // prepare query statement
        $stmt = $this->conn->prepare($query);
        // execute query
        $stmt->execute();
        return $stmt;
    }
	
	// create user
     function create() {
        // query to insert record
        $query = "INSERT INTO
                " . $this->table_name . "
            SET
                name=:name, username=:username";
        // prepare query
        $stmt = $this->conn->prepare($query);
        // sanitize
        $this->name = htmlspecialchars(strip_tags($this->name));
        $this->username = htmlspecialchars(strip_tags($this->username));

        // bind values
        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":username", $this->username);

        // execute query
        if ($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    } 
	
	// update the user
     function update() {
        // update query
        $query = "UPDATE
                " . $this->table_name . "
            SET
                name = :name, username = :username
            WHERE
                id = :id";

        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->name = htmlspecialchars(strip_tags($this->name));
        $this->username = htmlspecialchars(strip_tags($this->username));
        $this->id = htmlspecialchars(strip_tags($this->id));

        // bind new values
        $stmt->bindParam(':username', $this->username);
        $stmt->bindParam(':name', $this->name);
        $stmt->bindParam(':id', $this->id);

        // execute the query
        if ($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    } 
	
	// delete the user
     function delete() {
        // delete query
        $query = "DELETE FROM " . $this->table_name . " WHERE id = ?";

        // prepare query
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->id = htmlspecialchars(strip_tags($this->id));

        // bind id of record to delete
        $stmt->bindParam(1, $this->id);

        // execute query
        if ($stmt->execute()) {
            return true;
        }

        return false;
    } 
}
list.php
//list.php
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

//database and object files
include_once 'Db.php';
include_once 'User.php';

// instantiate database and user object
$database = new Db();
$db = $database->getConnection();

// initialize object
$user = new user($db);

// query user
$stmt = $user->read();
$num = $stmt->rowCount();

// check if more than 0 record found
if ($num > 0) {
    // user array
    $user_arr = array();
    $user_arr["records"] = array();

    // retrieve table contents
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // extract row
        extract($row);
        $user_item = array(
            "id" => $row['id'],
            "name" => $row['name'],
            "username" => $row['username']
        );
        array_push($user_arr["records"], $user_item);
    }
    echo json_encode($user_arr);
} else {
    echo json_encode(
            array("message" => "No products found.")
    );
}
?>
create.php
//create.php
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// database and object files
include_once 'Db.php';
include_once 'User.php';

$database = new Db();
$db = $database->getConnection();

// initialize object
$user = new User($db);

// get posted data
$data = json_decode(file_get_contents("php://input", true));

// set user property value
$user->name = $data->name;
$user->username = $data->username;

// create the user
if ($user->create()) {
    echo '{';
    echo '"message": "user was created."';
    echo '}';
}

// if unable to create the user, tell the user
else {
    echo '{';
    echo '"message": "Unable to create user."';
    echo '}';
}
?>
update.php
//update.php
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: PUT");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// database and object files
include_once 'Db.php';
include_once 'User.php';

$database = new Db();
$db = $database->getConnection();

// initialize object
$user = new User($db);

// get posted data
$data = json_decode(file_get_contents("php://input", true));

// set ID property of user to be updated
$user->id = $data->id;
// set user property value
$user->name = $data->name;
$user->username = $data->username;

// update the user
if ($user->update()) {
    echo '{';
    echo '"message": "user was updated."';
    echo '}';
}

// if unable to update the user, tell the user
else {
    echo '{';
    echo '"message": "Unable to update user."';
    echo '}';
}
?>
delete.php
//delete.php
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");


// database and object files
include_once 'Db.php';
include_once 'User.php';

$database = new Db();
$db = $database->getConnection();

// initialize object
$user = new User($db);

// set ID property of user to be deleted
$user->id = filter_input(INPUT_GET, 'id');

// delete the user
if ($user->delete()) {
    echo '{';
    echo '"message": "user was deleted."';
    echo '}';
}

// if unable to delete the user
else {
    echo '{';
    echo '"message": "Unable to delete user."';
    echo '}';
}
?>

Monday, October 25, 2021

Next.js How to setup a project

Next.js How to setup a project

What is Next.js
Next.js is the open source react framework which helps us to create static, dynamic and web applications. It’s used for server rendered applications, SEO website, PWA and many more.

Find more about the Next.js https://nextjs.org/

set up environment node --version

Create package.json and install dependencies : npm init -y

install next, react and react-dom in your project : npm install next react react-dom

Update scripts in package.json

"scripts": {
  "dev": "next",
  "build": "next build",
  "start": "next start"
}

dev next – Start Next.js project in development mode.
build next build – Build the application for production usage.
start next start – Start the Next.js production server.

Run project : npm run dev


nextjs/package.json
//nextjs/package.json
{
  "name": "nextjs",
  "version": "1.0.0",
  "description": "This is the first Next.js application",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "keywords": [],
  "author": "Cairocoders",
  "license": "ISC",
  "dependencies": {
    "next": "^11.1.2",
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  }
}
nodejs/pages/index.js
//nodejs/pages/index.js
const Index = () => <h1>Welcome to the First Next.js Application</h1>
 
export default Index;

SwiftUI Custom Search Bar Display

SwiftUI Custom Search Bar Display

ContentView.swift
//
//  ContentView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {

    @State var txt = ""
    
    var body: some View {
        
        ZStack {
            Color("Color").edgesIgnoringSafeArea(.all)
            SearchView(data: data, txt: $txt)
        }
    }
}

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

struct SearchView : View {
    
    var data : [String]
    @Binding var txt : String
    
    var body: some View {
        
        VStack(spacing :0) {
            ZStack {
                HStack {
                    TextField("Search", text: $txt)
                        .padding(.trailing, 75)
                }.padding()
                    .background(Color.white)
                
                if self.txt != "" {
                    HStack {
                        
                        Spacer()
                        
                        Button(action: {
                            self.txt = ""
                        }) {
                            Text("Cancel")
                        }.foregroundColor(.black)
                    }.padding()
                }
            }
            
            if self.txt != "" {
                List(self.data.filter{$0.lowercased().contains(self.txt.lowercased())},id: \.self) { rs in
                    Text(rs)
                }.frame(height: 500).listStyle(PlainListStyle())
            }
            
            Spacer()
        }.padding()
    }
}
Model.swift
//
//  Model.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import Foundation

var data = ["Afghanistan",
            "Aland Islands",
            "Albania",
            "Algeria",
            "American Samoa",
            "Andorra",
            "Angola",
            "Anguilla",
            "Antarctica",
            "Antigua and Barbuda",
            "Argentina",
            "Armenia",
            "Aruba",
            "Australia",
            "Austria",
            "Azerbaijan",
            "Bahamas",
            "Bahrain",
            "Bangladesh",
            "Barbados",
            "Belarus",
            "Belgium",
            "Belize",
            "Benin",
            "Bermuda",
            "Bhutan",
            "Bolivia",
            "Bonaire, Sint Eustatius and Saba",
            "Bosnia and Herzegovina",
            "Botswana",
            "Bouvet Island",
            "Brazil",
            "British Indian Ocean Territory",
            "Brunei Darussalam",
            "Bulgaria",
            "Burkina Faso",
            "Burundi",
            "Cambodia",
            "Cameroon",
            "Canada",
            "Cape Verde",
            "Cayman Islands",
            "Central African Republic",
            "Chad",
            "Chile",
            "China",
            "Christmas Island",
            "Cocos Keeling Islands",
            "Colombia",
            "Comoros",
            "Congo",
            "Congo, Democratic Republic of the Congo",
            "Cook Islands",
            "Costa Rica",
            "Cote D\"Ivoire",
            "Croatia",
            "Cuba",
            "Curacao",
            "Cyprus",
            "Czech Republic",
            "Denmark",
            "Djibouti",
            "Dominica",
            "Dominican Republic",
            "Ecuador",
            "Egypt",
            "El Salvador",
            "Equatorial Guinea",
            "Eritrea",
            "Estonia",
            "Ethiopia",
            "Falkland Islands Malvinas",
            "Faroe Islands",
            "Fiji",
            "Finland",
            "France",
            "French Guiana",
            "French Polynesia",
            "French Southern Territories",
            "Gabon",
            "Gambia",
            "Georgia",
            "Germany",
            "Ghana",
            "Gibraltar",
            "Greece",
            "Greenland",
            "Grenada",
            "Guadeloupe",
            "Guam",
            "Guatemala",
            "Guernsey",
            "Guinea",
            "Guinea-Bissau",
            "Guyana",
            "Haiti",
            "Heard Island and Mcdonald Islands",
            "Holy See Vatican City State",
            "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, Democratic People\"s Republic of",
            "Korea, Republic of",
            "Kosovo",
            "Kuwait",
            "Kyrgyzstan",
            "Lao People\"s Democratic Republic",
            "Latvia",
            "Lebanon",
            "Lesotho",
            "Liberia",
            "Libyan Arab Jamahiriya",
            "Liechtenstein",
            "Lithuania",
            "Luxembourg",
            "Macao",
            "Macedonia, the Former Yugoslav Republic of",
            "Madagascar",
            "Malawi",
            "Malaysia",
            "Maldives",
            "Mali",
            "Malta",
            "Marshall Islands",
            "Martinique",
            "Mauritania",
            "Mauritius",
            "Mayotte",
            "Mexico",
            "Micronesia, Federated States of",
            "Moldova, Republic of",
            "Monaco",
            "Mongolia",
            "Montenegro",
            "Montserrat",
            "Morocco",
            "Mozambique",
            "Myanmar",
            "Namibia",
            "Nauru",
            "Nepal",
            "Netherlands",
            "Netherlands Antilles",
            "New Caledonia",
            "New Zealand",
            "Nicaragua",
            "Niger",
            "Nigeria",
            "Niue",
            "Norfolk Island",
            "Northern Mariana Islands",
            "Norway",
            "Oman",
            "Pakistan",
            "Palau",
            "Palestinian Territory, Occupied",
            "Panama",
            "Papua New Guinea",
            "Paraguay",
            "Peru",
            "Philippines",
            "Pitcairn",
            "Poland",
            "Portugal",
            "Puerto Rico",
            "Qatar",
            "Reunion",
            "Romania",
            "Russian Federation",
            "Rwanda",
            "Saint Barthelemy",
            "Saint Helena",
            "Saint Kitts and Nevis",
            "Saint Lucia",
            "Saint Martin",
            "Saint Pierre and Miquelon",
            "Saint Vincent and the Grenadines",
            "Samoa",
            "San Marino",
            "Sao Tome and Principe",
            "Saudi Arabia",
            "Senegal",
            "Serbia",
            "Serbia and Montenegro",
            "Seychelles",
            "Sierra Leone",
            "Singapore",
            "Sint Maarten",
            "Slovakia",
            "Slovenia",
            "Solomon Islands",
            "Somalia",
            "South Africa",
            "South Georgia and the South Sandwich Islands",
            "South Sudan",
            "Spain",
            "Sri Lanka",
            "Sudan",
            "Suriname",
            "Svalbard and Jan Mayen",
            "Swaziland",
            "Sweden",
            "Switzerland",
            "Syrian Arab Republic",
            "Taiwan, Province of China",
            "Tajikistan",
            "Tanzania, United Republic of",
            "Thailand",
            "Timor-Leste",
            "Togo",
            "Tokelau",
            "Tonga",
            "Trinidad and Tobago",
            "Tunisia",
            "Turkey",
            "Turkmenistan",
            "Turks and Caicos Islands",
            "Tuvalu",
            "Uganda",
            "Ukraine",
            "United Arab Emirates",
            "United Kingdom",
            "United States",
            "United States Minor Outlying Islands",
            "Uruguay",
            "Uzbekistan",
            "Vanuatu",
            "Venezuela",
            "Viet Nam",
            "Virgin Islands, British",
            "Virgin Islands, U.s.",
            "Wallis and Futuna",
            "Western Sahara",
            "Yemen",
            "Zambia",
            "Zimbabwe"]

SwiftUI Expandable Floating Action Button

SwiftUI Expandable Floating Action Button

ContentView.swift
 
//
//  ContentView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var show = false
    
    var body: some View {
        
        ZStack {
            
            List(0..<20) { list in
               Text("List View \(list)")
            }
            VStack {
                
                Spacer()
                
                HStack {
                    
                    Spacer()
                    
                    FloatingActionButton(show: $show)
                        .padding(.trailing, 30)
                }.padding([.bottom], 20)
            }
        }
    }
}

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

struct FloatingActionButton : View {
    
    @Binding var show : Bool
    
    var body: some View {
        
        VStack(spacing : 20) {
            
            if self.show {
                
                Button(action: {
                    self.show.toggle()
                }) {
                    Image(systemName: "video").resizable().frame(width: 25, height: 15).padding(22)
                }
                .background(Color.gray)
                .foregroundColor(Color.white)
                .clipShape(Circle())
                
                Button(action: {
                    self.show.toggle()
                }) {
                    Image(systemName: "message").resizable().frame(width: 25, height: 15).padding(22)
                }
                .background(Color.gray)
                .foregroundColor(Color.white)
                .clipShape(Circle())
                
                Button(action: {
                    self.show.toggle()
                }) {
                    Image(systemName: "person.badge.plus").resizable().frame(width: 25, height: 15).padding(22)
                }
                .background(Color.gray)
                .foregroundColor(Color.white)
                .clipShape(Circle())
            }
            Button(action: {
                self.show.toggle()
            }) {
                Image(systemName: "chevron.up").resizable().frame(width: 25, height: 15).padding(22)
            }
            .background(Color.green)
            .foregroundColor(Color.white)
            .clipShape(Circle())
            .rotationEffect(.init(degrees: self.show ? 180 : 0))
        }.animation(.spring())
    }
}

Sunday, October 24, 2021

ReactJS Axios and PHP Mysql File Upload - Axios Post

ReactJS Axios and PHP Mysql File Upload - Axios Post

https://github.com/axios/axios

Installing the Axios Client
$ npm install axios

C:\reactdev\myreactdev>npm install axios

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

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

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

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

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

class App extends React.Component {
    render() {
        return (
            <FileUploadForm />
        );
    }
}
export default App;
src/FileUploadForm.js
//src/FileUploadForm.js
import React from 'react'
import axios from 'axios';

class FileUploadForm extends React.Component {

    UPLOAD_ENDPOINT = 'http://localhost/devtest/reactjs/upload.php';
    constructor(props) {
        super(props);
        this.state ={
          file:null
        }
        this.onSubmit = this.onSubmit.bind(this)
        this.onChange = this.onChange.bind(this)
        this.uploadFile = this.uploadFile.bind(this)
    }
    async onSubmit(e){
        e.preventDefault() 
        let res = await this.uploadFile(this.state.file);
        console.log(res.data);
    }
    onChange(e) {
        this.setState({file:e.target.files[0]})
    }
    async uploadFile(file){
        const formData = new FormData();
        formData.append('avatar',file)
        return  await axios.post(this.UPLOAD_ENDPOINT, formData,{
            headers: {
                'content-type': 'multipart/form-data'
            }
        });
    }
    
      render() {
        return (
          <div className="container" style={{padding: 20}}>
            <h1> ReactJS Axios and PHP Mysql File Upload - Axios Post </h1>
            <div className="row">
            <form onSubmit={ this.onSubmit } className="form-inline">
                <div className="form-group">
                <label>Choose File to Upload: </label>
                <input type="file" className="form-control" onChange={ this.onChange } />
                </div> <br/>
                <button type="submit" className="btn btn-success" >Upload File</button>
            </form>
          </div>
          </div>
       )
      } 
}
export default FileUploadForm;
http://localhost/devtest/reactjs/upload.php
//http://localhost/devtest/reactjs/upload.php
<?php 
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");

$response = array();
$upload_dir = 'uploads/';
$server_url = 'http://localhost/devtest/reactjs/';

if($_FILES['avatar'])
{
    $avatar_name = $_FILES["avatar"]["name"];
    $avatar_tmp_name = $_FILES["avatar"]["tmp_name"];
    $error = $_FILES["avatar"]["error"];

    if($error > 0){
        $response = array(
            "status" => "error",
            "error" => true,
            "message" => "Error uploading the file!"
        );
    }else 
    {
        $random_name = rand(1000,1000000)."-".$avatar_name;
        $upload_name = $upload_dir.strtolower($random_name);
        $upload_name = preg_replace('/\s+/', '-', $upload_name);
    
        if(move_uploaded_file($avatar_tmp_name , $upload_name)) {
            $response = array(
                "status" => "success",
                "error" => false,
                "message" => "File uploaded successfully",
                "url" => $server_url."/".$upload_name
              );
              
            $host = "localhost"; 
            $user = "root"; 
            $password = ""; 
            $dbname = "testingdb"; 
              
            $con = mysqli_connect($host, $user, $password,$dbname);  

            if (!$con) {
                die("Connection failed: " . mysqli_connect_error());
            }

            $sql = "insert into users (username, name, photo) values ('cairocoders', 'cairocoders Ednalan', '$upload_name')"; 
            mysqli_query($con,$sql);
        }else
        {
            $response = array(
                "status" => "error",
                "error" => true,
                "message" => "Error uploading the file!"
            );
        }
    }

}else{
    $response = array(
        "status" => "error",
        "error" => true,
        "message" => "No file was sent!"
    );
}

echo json_encode($response);
?>

Saturday, October 23, 2021

ReactJS PHP Mysql and Axios Add data and list data - axios get and axios post

ReactJS PHP Mysql and Axios Add data and list data - axios get and axios post

https://github.com/axios/axios

The componentDidMount() life-cycle hook. This is executed when your React component is inserted/mounted in the DOM.

Installing the Axios Client
$ npm install axios

C:\reactdev\myreactdev>npm install axios

header("Access-Control-Allow-Origin: *"); add this CORS header to enable any domain to send HTTP requests to these endpoints:

CREATE TABLE `contacts` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(150) NOT NULL,
  `city` varchar(150) NOT NULL,
  `country` varchar(150) NOT NULL,
  `job` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `contacts` (`id`, `name`, `email`, `city`, `country`, `job`) VALUES
(36, 'Cara Stevens', 'cairocoders@gmail.com', 'Olongapo City', 'Phil', 'coders'),
(37, 'Airi Satou', 'AiriSatou@gmail.com', 'Tokyo', 'Japan', 'Accountant'),
(38, 'Angelica Ramos', 'AngelicaRamos@gmail.com', 'London', 'United Kingdom', 'Chief Executive Officer'),
(39, 'Ashton Cox', 'AshtonCox@gmail.com', 'San Francisco', 'USA', 'Junior Technical Author');

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

ALTER TABLE `contacts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=40;

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React from 'react';
import axios from 'axios';

class App extends React.Component {
  state = {
    name: '',
    email: '',
    country: '',
    city: '',
    job: '',
    contacts: []
  }

  componentDidMount() {
    const url = 'http://localhost/devtest/reactjs/contacts.php/'
    axios.get(url).then(response => response.data)
    .then((data) => {
      this.setState({ contacts: data })
      console.log(this.state.contacts)
     })
  }

  handleFormSubmit( event ) {
      event.preventDefault();

      let formData = new FormData();
      formData.append('name', this.state.name)
      formData.append('email', this.state.email)
      formData.append('city', this.state.city)
      formData.append('country', this.state.country)
      formData.append('job', this.state.job)

      axios({
          method: 'post',
          url: 'http://localhost/devtest/reactjs/contacts.php/',
          data: formData,
          config: { headers: {'Content-Type': 'multipart/form-data' }}
      })
      .then(function (response) {
          //handle success
          console.log(response)
          alert('New Contact Successfully Added.');  
      })
      .catch(function (response) {
          //handle error
          console.log(response)
      });
  }

  render() {
    return (
      <div className="container">
        <h1 className="page-header text-center">Contact Management</h1>
        
        <div className="col-md-4">
            <div className="panel panel-primary">
                <div className="panel-heading"><span className="glyphicon glyphicon-user"></span> Add New Contact</div>
                <div className="panel-body">
                <form>
                <label>Name</label>
                <input type="text" name="name" className="form-control" value={this.state.name} onChange={e => this.setState({ name: e.target.value })}/>

                <label>Email</label>
                <input type="email" name="email" className="form-control" value={this.state.email} onChange={e => this.setState({ email: e.target.value })}/>

                <label>Country</label>
                <input type="text" name="country" className="form-control" value={this.state.country} onChange={e => this.setState({ country: e.target.value })}/>

                <label>City</label>
                <input type="text" name="city" className="form-control" value={this.state.city} onChange={e => this.setState({ city: e.target.value })}/>

                <label>Job</label>
                <input type="text" name="job" className="form-control" value={this.state.job} onChange={e => this.setState({ job: e.target.value })}/>
                <br/>
                <input type="submit" className="btn btn-primary btn-block" onClick={e => this.handleFormSubmit(e)} value="Create Contact" />
            </form>
                </div>
            </div>
        </div>

        <div className="col-md-8">  
        <h3>Contact Table</h3>
        <table className="table table-bordered table-striped">
        <thead>  
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Country</th>
            <th>City</th>
            <th>Job</th>     
        </tr>
        </thead>
        <tbody>
        {this.state.contacts.map((contact, index) => (
        <tr key={index}>
            <td>{ contact.name }</td>
            <td>{ contact.email }</td>
            <td>{ contact.country }</td>
            <td>{ contact.city }</td>
            <td>{ contact.job }</td>
        </tr>
        ))}
        </tbody>
        </table>
         </div>  

        </div>
    );
  }
}
export default App;
http://localhost/devtest/reactjs/contacts.php/
//http://localhost/devtest/reactjs/contacts.php/
<?php
header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 
$id = '';

$con = mysqli_connect($host, $user, $password,$dbname);

$method = $_SERVER['REQUEST_METHOD'];


if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
    case 'GET':
      $sql = "select * from contacts"; 
      break;
    case 'POST':
      $name = $_POST["name"];
      $email = $_POST["email"];
      $country = $_POST["country"];
      $city = $_POST["city"];
      $job = $_POST["job"];

      $sql = "insert into contacts (name, email, city, country, job) values ('$name', '$email', '$city', '$country', '$job')"; 
      break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'GET') {
    if (!$id) echo '[';
    for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
      echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
    }
    if (!$id) echo ']';
  } elseif ($method == 'POST') {
    echo json_encode($result);
  } else {
    echo mysqli_affected_rows($con);
  }

$con->close();

ReactJS PHP Mysql and Axios List all data - axios get localhost/employees.php

ReactJS PHP Mysql and Axios List all data - axios get localhost/employees.php

The componentDidMount() life-cycle hook. This is executed when your React component is inserted/mounted in the DOM.

Installing the Axios Client
$ npm install axios

C:\reactdev\myreactdev>npm install axios

https://github.com/axios/axios


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;

--
-- Dumping data for table `employee`
--

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;


src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

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

class App extends Component {
  state = {
    employees: []
  }
  componentDidMount() {
    const url = 'http://localhost/devtest/reactjs/employees.php/'
    axios.get(url).then(response => response.data)
    .then((data) => {
      this.setState({ employees: data })
      console.log(this.state.employees)
     })
  }
  render() {
 
    return (
       <div className="container" style={{padding: 20}}>
        <div className="col-xs-8">
        <h1>ReactJS PHP Mysql and Axios List all data - localhost/employees.php</h1>
        <table className="table table-striped">
          <thead className="thead-light ">
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
          </thead>
          <tbody>
          {this.state.employees.map((rs, index) => (
            <tr key={index}>
              <td>{rs.name}</td>
              <td>{rs.position}</td>
              <td>{rs.office}</td>
              <td>{rs.age}</td>
              <td>$ {rs.salary}</td>
            </tr>
            ))}
          </tbody>
        </table>
        </div>
       </div>
    );
  }
}
export default App;
http://localhost/devtest/reactjs/employees.php/
//devtest/reactjs/employees.php
<?php
header("Access-Control-Allow-Origin: *");
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 
$id = '';

$con = mysqli_connect($host, $user, $password,$dbname);

$method = $_SERVER['REQUEST_METHOD'];

if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
    case 'GET':
      $sql = "select * from employee"; 
      break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'GET') {
    if (!$id) echo '[';
    for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
      echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
    }
    if (!$id) echo ']';
  } elseif ($method == 'POST') {
    echo json_encode($result);
  } else {
    echo mysqli_affected_rows($con);
  }

$con->close();

Related Post