article

Showing posts with label VueJS. Show all posts
Showing posts with label VueJS. Show all posts

Thursday, August 31, 2023

Laravel 10 Vue JS Vite CRUD ( Create Read Update and Delete)

Laravel 10 Vue JS Vite CRUD ( Create Read Update and Delete)

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel10project>composer create-project laravel/laravel laravel10project

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel10db
DB_USERNAME=root
DB_PASSWORD=

Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\my-app>php artisan migrate

Migration table created successfully.

check database table

Create Model and Migration

C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Student -m

A new file named Student.php will be created in the app directory and database/migrations directory to generate the table in our database
app/Models/Student.php
//app/Models/Student.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;

    protected $fillable = [
          'name',
          'address',
          'phone',
    ];
}
database\migrations\create_students_table.php
//database\migrations\create_students_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('address');
            $table->string('phone')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('students');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravel10project>php artisan migrate

Create Controller
php artisan make:controller StudentController
C:\xampp\htdocs\laravel\my-app>php artisan make:controller StudentController --api

app/Http/Controllers/StudentController.php
//app/Http/Controllers/StudentController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller
{
    protected $student;
    public function __construct(){
        $this->student = new Student();
        
    }

    public function index()
    {
        return $this->student->all();
    }

    public function store(Request $request)
    {
        return $this->student->create($request->all());
    }

    public function show(string $id)
    {
        $student = $this->student->find($id);  
    }

    public function update(Request $request, string $id)
    {
        $student = $this->student->find($id);
        $student->update($request->all());
        return $student;
    }

    public function destroy(string $id)
    {
        $student = $this->student->find($id);
        return $student->delete();
    }
}
Routes
routes/api.php
//routes/api.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::apiResource('/student', StudentController::class);
Run C:\xampp\htdocs\laravel\my-app>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Vue using vite install Vue using vite
C:\xampp\htdocs\laravel\my-app> npm create vite@latest
Need to install the following packages:
create-vite@4.4.1
Ok to proceed? (y) y
√ Project name: ... vite-project
√ Select a framework: » Vue
√ Select a variant: » JavaScript

Scaffolding project in C:\xampp\htdocs\laravel\my-app\vite-project...

Done. Now run:

cd vite-project
npm install
npm run dev
PS C:\xampp\htdocs\laravel\my-app> cd vite-project
PS C:\xampp\htdocs\laravel\my-app\vite-project> npm install
PS C:\xampp\htdocs\laravel\my-app\vite-project> npm run dev

Local: http://localhost:5173/

Install axios
https://github.com/axios/axios#axios-api
PS C:\xampp\htdocs\laravel\my-app\vite-project> $ npm install axios

inside Components folder create file Student.vue

vite-project/src/components/Student.vue
//vite-project/src/components/Student.vue
<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-10">
                <h3 class="text-center text-dark mt-2">Laravel 10 Vue JS Vite CRUD ( Create Read Update and Delete)</h3>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4">
                <div class="card-header">
                    Add Record
                </div>
                <div class="card-body">
                    <form @submit.prevent="save">
                    
                    <div class="form-group">
                        <label>Student name</label>
                        <input type="text" v-model="student.name" class="form-control"  placeholder="Student name">
                    
                    </div>
                    <div class="form-group">
                        <label>Student Address</label>
                        <input type="text" v-model="student.address" class="form-control"  placeholder="Student Address">
                    
                    </div>
                    
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="text" v-model="student.phone" class="form-control"  placeholder="Phone">
                    
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Save</button>
                    </form>
                </div>
            </div>
            <div class="col-md-8">
                <h2>Student List</h2>
                    <table class="table table-dark">
                    <thead>
                        <tr>
                        <th scope="col">ID</th>
                        <th scope="col">Student Name</th>
                        <th scope="col">Address</th>
                        <th scope="col">Phone</th>
                        <th scope="col">Option</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="student in result" v-bind:key="student.id">
                            
                            <td>{{ student.id }}</td>
                            <td>{{ student.name }}</td>
                            <td>{{ student.address }}</td>
                            <td>{{ student.phone }}</td>
                            <td>
                                <button type="button" class="btn btn-warning" @click="edit(student)">Edit</button>
                                <button type="button" class="btn btn-danger"  @click="remove(student)">Delete</button>
                            </td>
                            </tr>
                        
                    </tbody>
                    </table>
            </div>
        </div>
    </div>    
</template>
<script>
import axios from 'axios';
 
export default {
    name: 'Student',
    data () {
      return {
        result: {},
        student:{
                   id: '',
                   name: '',
                   address: '',
                   phone: ''
 
 
        }
      }
    },
    created() { 
        this.StudentLoad();
    },
    mounted() {
          console.log("mounted() called.......");
    },
 
    methods: {
           StudentLoad()
           {
                 var page = "http://127.0.0.1:8000/api/student";
                 axios.get(page)
                  .then(
                      ({data})=>{
                        console.log(data);
                        this.result = data;
                      }
                  );
           },
           
           save()
           {
            if(this.student.id == '')
              {
                this.saveData();
              }
              else
              {
                this.updateData();
              }       
 
           },
           saveData()
           {
            axios.post("http://127.0.0.1:8000/api/student", this.student)
            .then(
              ({data})=>{
                alert("saved");
                this.StudentLoad();
                this.student.name = '';
                this.student.address = '',
                this.student.phone = ''
                this.id = ''
              }
            )
 
           },
           edit(student)
           {
            this.student = student;
           },
           updateData()
           {
              var editrecords = 'http://127.0.0.1:8000/api/student/'+ this.student.id;
              axios.put(editrecords, this.student)
              .then(
                ({data})=>{
                  this.student.name = '';
                  this.student.address = '',
                  this.student.phone = ''
                  this.id = ''
                  alert("Updated!!!");
                  this.StudentLoad();
                }
              );
 
           },
 
           remove(student){
              var url = `http://127.0.0.1:8000/api/student/${student.id}`;
              // var url = 'http://127.0.0.1:8000/api/student/'+ student.id;
              axios.delete(url);
              alert("Deleted");
              this.StudentLoad();
            }
      }
  }
  </script>
update App.vue
vite-project/src/App.vue
//vite-project/src/App.vue
<script setup>
import Student from './components/Student.vue'
</script>

<template>
<Student />
</template>
Open index.html and add bootstrap url
vite-project/index.html
//vite-project/index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
    <title>Vite + Vue</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>
open vite-project/src/main.js uncomment style.css
Run C:\xampp\htdocs\laravel\my-app\vite-project> npm run dev
http://localhost:5173/

Saturday, September 3, 2022

Laravel 9 vue 3 Todo List - Create Read Update and Delete

Laravel 9 vue 3 Todo List - Create Read Update and Delete

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Create Model and Migration:
C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Item -m
app/Models/Item.php
laravelproject\database\migrations\create_items_table.php
//laravelproject\database\migrations\create_items_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->boolean("completed")->default(false);
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('items');
    }
};
Database Migration

php artisan migrate

C:\xampp\htdocs\laravel\laravelproject>php artisan migrate
Migration table created successfully.
check database table

Creating Controller
C:\xampp\htdocs\laravel\laravelproject>php artisan make:controller ItemController --resource

app/Http/Controllers/ItemController.php
//app/Http/Controllers/ItemController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Item;
use Illuminate\Support\Carbon;

class ItemController extends Controller
{
    public function index()
    {
       return Item::orderBy('created_at', 'desc')->get();
    }
    public function store(Request $request)
    {
        $newItem = new Item;
        $newItem->name = $request->item['name'];
        $newItem->save();

        return $newItem;
    }
    public function update(Request $request, $id)
    {
        $existingItem = Item::find($id);  

        if($existingItem){
           $existingItem->completed = $request->item['completed'] ? true : false;
           $existingItem->updated_at = Carbon::now() ;
           $existingItem->save();
           return $existingItem;

        } 
        return "Item not found";
    }
    public function destroy($id)
    {
        $existingItem = Item::find($id);
        if($existingItem){
           $existingItem->delete();
           return "Item deleted";
        }
        return "Item not found";
    }
}
Edit API Routes laravelproject\routes\api.php
//laravelproject\routes\api.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ItemController;

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('/items', [ItemController::class, 'index']);
Route::prefix('/item')->group(function(){
    Route::post('/store',[ItemController::class, 'store']);
    Route::put('/{id}' , [ItemController::class, 'update']);
    Route::delete('/{id}', [ItemController::class, 'destroy'] );
});
Run C:\xampp\htdocs\laravel\laravelproject>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Check API Results in Postman
https://www.postman.com/downloads/

Headers ( Content-Type : application/json )
POST method : http://127.0.0.1:8000/api/item/store
Get method : http://127.0.0.1:8000/api/items
PUT method : http://127.0.0.1:8000/api/item/1
DELTE method : http://127.0.0.1:8000/api/item/1
Frontend Vue js 3
Install Vue 3

npm install vue@next
npm install
npm i vue-loader
npm run dev

create components folder under resources/assets/js/
create vue file Welcome.vue laravelproject\resources\js\components\Welcome.vue
laravelproject\resources\js\components\Welcome.vue
//laravelproject\resources\js\components\Welcome.vue
<template>
    <div class="container w-100 m-auto text-center mt-3">
        <h1 class="text-danger">Laravel vue todo list</h1>
        <add-item-form v-on:reloadlist="getItems()" />
        <list-view
            :items="items"
            v-on:reloadlist="getItems()"
            class="text-center"
        />
    </div>
</template>
<script>
    import listView from "./listView";
    import addItemForm from "./addItemForm";

    export default {
        components: {
            addItemForm,
            listView
        },

        data: function() {
            return {
                items: []
            };
        },
        methods: {
            getItems() {
                axios
                    .get("api/items")
                    .then(res => {
                        this.items = res.data;
                    })
                    .catch(error => {
                        console.log(error);
                    });
            }
        },
        created() {
            this.getItems();
        }
    };
</script>
open webpack.mix.js root directory and add .vue()
mix.js('resources/js/app.js', 'public/js')
.vue()
Next, Go to resources/assets/js then open app.js file and intialize vue js components in this file.

open app.js file and update the following code into your app.js file:
laravelproject\resources\js\app.js
//laravelproject\resources\js\app.js
import './bootstrap';

import { createApp } from 'vue';
import Welcome from './components/Welcome'
  
const app = createApp({})
  
app.component('welcome', Welcome)
  
app.mount('#app')
Open welcome.blade.php file
laravelproject\resources\view\welcome.blade.php
//laravelproject\resources\view\welcome.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel 9 VUE 3</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
    <link href="{{ mix('css/app.css') }}" rel="stylesheet">
</head>
<body>
       
    <div id="app">
    <div class="card-body">        
        <welcome></welcome>
    </div>
    </div>
    <script src="{{ mix('js/app.js') }}" defer></script>
</body>
</html>
AddItemForm.vue
laravelproject\resources\js\components\AddItemForm.vue
//laravelproject\resources\js\components\AddItemForm.vue
<template>
    <div class="mt-3">
        <h2>add item form</h2>
        <div class="container m-2 w-100">
            <input
                type="test"
                placeholder="add item"
                class="border"
                v-model="item.name"
            />
            <button
                :class="[item.name ? 'active' : 'notactive']"
                @click="addItem()"
            >
                add +
            </button>
        </div>
    </div>
</template>
<script>
export default {
    data: function() {
        return {
            item: {
                name: ""
            }
        };
    },
    methods: {
        addItem() {
            if (this.item.name == "") {
                return;
            }
            axios
                .post("api/item/store", {
                    item: this.item
                })
                .then(res => {
                    if (res.status == 201) {
                        this.item.name = "";
                        this.$emit("reloadlist");
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        }
    }
};
</script>

<style scoped>
.active {
    color: white;
    background-color: blue;
}
.inactive {
    color: gray;
}
</style>
listItem.vue
laravelproject\resources\js\components\listItem.vue
//laravelproject\resources\js\components\listItem.vue
<template>
    <li class="list-group-item d-flex justify-content-between w-50">
        <input
            type="checkbox"
            @change="updateCheck()"
            v-model="item.completed"
            class="mr-3"
        />
        <span :class="[item.completed ? 'completed' : '', 'item']">{{
            item.name
        }}</span>
        <button class="btn-danger ml-3" @click="removeItem()">X</button>
    </li>
</template>

<script>
export default {
    props: ["item"],
    methods: {
        updateCheck() {
            axios
                .put(`api/item/${this.item.id}`, {
                    item: this.item
                })
                .then(res => {
                    if (res.status == 200) {
                        this.$emit("itemchanged");
                    }
                })
                .catch(error => {
                    console.log("error from axios put", errors);
                });
        },
        removeItem() {
            axios
                .delete(`api/item/${this.item.id}`)
                .then(res => {
                    if (res.status == 200) {
                        this.$emit("itemchanged");
                    }
                })
                .catch(error => {
                    console.log("error from axios delte ", error);
                });
        }
    }
};
</script>

<style>
.completed {
    text-decoration: line-through;
    color: gray;
}
.item {
    word-break: break-all;
}
</style>
listView.vue
laravelproject\resources\js\components\listView.vue
//laravelproject\resources\js\components\listView.vue
<template>
    <div class="mt-4">
        <h4>list view</h4>
        <hr class="w-50 m-auto mb-3" />
        <ul class="list-group m-auto">
            <list-item
                :item="item"
                v-on:itemchanged="$emit('reloadlist')"
                v-for="item in items"
                :key="item.id"
                class="m-auto my-1 text-justify text-wrap"
            />
        </ul>
    </div>
</template>

<script>
import listItem from "./listItem";

export default {
    components: {
        listItem
    },
    props: ["items"]
};
</script>
Run Development Server

C:\xampp\htdocs\laravel\laravelproject>npm run dev

C:\xampp\htdocs\laravel\laravelproject>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Friday, March 11, 2022

Vuejs Vue CLI File Upload with Axios and PHP

Vuejs Vue CLI File Upload with Axios and PHP

Install vue-axios
npm install --save axios vue-axios
https://www.npmjs.com/package/vue-axios

C:\vuejs\myapp>npm install --save axios vue-axios
C:\vuejs\myapp>npm run serve
src/main.js
//src/main.js
import { createApp } from 'vue'
import App from './App.vue'

import axios from 'axios' // C:\vuejs\myapp>npm install --save axios vue-axios

import VueAxios from 'vue-axios'


createApp(App).use(VueAxios, axios).mount('#app')
src/components/fileUpload.vue
//src/components/fileUpload.vue
<template>
  <div class="container">
    <div class="row">
      <h1>Vuejs Vue CLI File Upload with Axios and PHP</h1>
      <label>File
        <input type="file" id="file" ref="file"/>
      </label>
        <button v-on:click="uploadFile()">Upload</button>
    </div>
  </div>
</template>

<script>

  export default  {   
      data () {
      return {          
          file:''
      }    
    },
    methods: {     

            uploadFile: function(){

                 this.file = this.$refs.file.files[0];                  
                 let formData = new FormData();
                 formData.append('file', this.file);
                 this.$refs.file.value = '';
                this.axios.post('http://localhost/devtest/upload.php', formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                .then(function (response) {

                    if(!response.data){
                        alert('File not uploaded.');
                    }else{
                        alert('File uploaded successfully.');                        

                    }

                })
                .catch(function (error) {
                    console.log(error);
                 });

            }
    },
    
}
</script>
src/App.vue
//src/App.vue
<template>
  <div id="app">
      <FileUpload/>
  </div>
</template>
<script>
import FileUpload from './components/fileUpload.vue'
 
      export default {
                 name: 'app',
                       components: {
                             FileUpload
                }
       }
</script>
upload.php
//upload.php
<?php  
    header('Access-Control-Allow-Origin: *');  
     $filename = $_FILES['file']['name'];
     $allowed_extensions = array('jpg','jpeg','png','pdf');
      $extension = pathinfo($filename, PATHINFO_EXTENSION);
       if(in_array(strtolower($extension),$allowed_extensions) ) {     
          if(move_uploaded_file($_FILES['file']['tmp_name'], "upload/".$filename)){
                echo 1;
          }else{
              echo 0;
          }
    }else{
        echo 0;
    } 
?>

Wednesday, March 9, 2022

Vue.js PHP Mysql Filter records by Date range

Vue.js PHP Mysql Filter records by Date range

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

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

Axios  
https://www.npmjs.com/package/axios
CDN : https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

vuejs-datepicker
https://www.npmjs.com/package/vuejs-datepicker
https://unpkg.com/vuejs-datepicker

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,
  `date_of_join` date NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

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

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


index.html
//index.html
<!doctype html>
<html>
	<head>
		<title>Vue.js PHP Mysql Filter records by Date range</title>
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/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>
		<script src="https://unpkg.com/vuejs-datepicker"></script>
		<style type="text/css">
		.inline{
			display: inline-block;
		}
		</style>
	</head>
	<body>
    <div class="container" id='myapp'>
        <div class="row">
            <div class="col-md-12 mt-5">
                <h1 class="text-center">Vue.js PHP Mysql Filter records by Date range</h1>
                <hr>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-6">
                        <div class="input-group mb-3">
                            <div class="input-group-prepend">
                                <span class="input-group-text bg-info text-white" id="basic-addon1"><i class="fas fa-calendar-alt"></i></span>
                            </div>
							<vuejs-datepicker wrapper-class="inline" placeholder="From date" format="dd/MM/yyyy" :clear-button="true" v-model='fromdate' @closed='checkDate();'></vuejs-datepicker>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="input-group mb-3">
                            <div class="input-group-prepend">
                                <span class="input-group-text bg-info text-white" id="basic-addon1"><i class="fas fa-calendar-alt"></i></span>
                            </div>
                            <vuejs-datepicker wrapper-class="inline" placeholder="To date" format="dd/MM/yyyy" :clear-button="true" v-model='todate' @closed='checkDate();' ></vuejs-datepicker>
                        </div>
                    </div>
                </div>
                <div>
					<input type='button' class="btn btn-outline-info btn-sm" @click='fetchRecords()' value='Search'>
                    <button id="reset" class="btn btn-outline-warning btn-sm">Reset</button>
                </div>
                <div class="row mt-3">
                    <div class="col-md-12">
                        <div class="table-responsive">
                            <table class="table table-striped table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Position</th>
                                        <th>Office</th>
                                        <th>Salary</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
								<tbody>
									<tr v-for='employee in employees'>
										<td>{{ employee.id }}</td>
										<td>{{ employee.name }}</td>
										<td>{{ employee.position }}</td>
										<td>{{ employee.office }}</td>
										<td>{{ employee.salary }}</td>
										<td>{{ employee.date_of_join }}</td>
									</tr>

									<tr v-show="recordNotFound">
										<td colspan='6'>No record found.</td>
									</tr>
								</tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Font Awesome -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script>
	<script>
			var app = new Vue({
				el: '#myapp',
				data: {
					fromdate: "",
					todate: "",
					employees: "",
					recordNotFound: true
				},
				methods: {
					checkDate: function(){

						if(this.fromdate != ''){
							var fromdate = new Date(this.fromdate);
							var todate = new Date(this.todate);

							if(fromdate.getTime() > todate.getTime()){
								var currentDate = new Date();

		  						var day = fromdate.getDate(); 
		  						var month = fromdate.getMonth(); 
								var year = fromdate.getFullYear();

								this.todate = new Date(year, month,  day);
							}
							
						}
						
					},
					fetchRecords: function(){
						
						if(this.fromdate !='' && this.todate != ''){
							
							axios.get('ajaxfile.php', {
							    params: {
							      	fromdate: this.fromdate,
							      	todate: this.todate
							    }
							})
						  	.then(function (response) {
								console.log(response);
								
						    	app.employees = response.data;

						    	// Display no record found <tr> if record not found
						    	if(app.employees.length == 0){
						    		app.recordNotFound = true;
						    	}else{
						    		app.recordNotFound = false;
						    	}
						  	})
						  	.catch(function (error) {
						    	console.log(error);
						  	});
						
						}

					}
				},
				components: {
				  	vuejsDatepicker
				}
			})

		</script>
	</body>
</html>
config.php
//config.php
 <?php
$host = "localhost";  
$user = "root";       
$password = "";         
$dbname = "testingdb";   

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

// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}
ajaxfile.php
//ajaxfile.php
<?php
include "config.php";

$condition  = "1";
if( (isset($_GET['fromdate']) && $_GET['fromdate'] != '' ) && 
	(isset($_GET['todate'])  && $_GET['todate'] != '' ) ){
	$condition  = " date_of_join between '".$_GET['fromdate']."' and '".$_GET['todate']."' ";
}
$userData = mysqli_query($con,"select * from employee WHERE ".$condition );

$response = array();

while($row = mysqli_fetch_assoc($userData)){

    $response[] = array("id"=>$row['id'],"name" => $row['name'],"date_of_join" => $row['date_of_join'],"position" => $row['position'],"office" => $row['office'],"salary" => $row['salary']);

}

echo json_encode($response);
exit;

Thursday, February 24, 2022

Vue.js Form Login validation

Vue.js Form Login validation

Bootstrap 4.0 Version
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

vuejs
https://v2.vuejs.org/v2/guide/installation.html
CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js
login.html
//login.html
<!DOCTYPE html>
<html>
<head>
<title>Vue.js Form Login validation</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body>
<div class="container mt-5">
    <div class="row d-flex justify-content-center">
        <div class="col-md-6"><p><h2>Vue.js Form Login validation<h2></p>
            <div class="card px-5 py-5" id="formvalidation">
                <div class="form-data" v-if="!submitted">
                    <div class="forms-inputs mb-4"> <span>Email or username</span> <input autocomplete="off" type="text" v-model="email" v-bind:class="{'form-control':true, 'is-invalid' : !validEmail(email) && emailBlured}" v-on:blur="emailBlured = true">
                        <div class="invalid-feedback">A valid email is required!</div>
                    </div>
                    <div class="forms-inputs mb-4"> <span>Password</span> <input autocomplete="off" type="password" v-model="password" v-bind:class="{'form-control':true, 'is-invalid' : !validPassword(password) && passwordBlured}" v-on:blur="passwordBlured = true">
                        <div class="invalid-feedback">Password must be 8 character!</div>
                    </div>
                    <div class="mb-3"> <button v-on:click.stop.prevent="submit" class="btn btn-dark w-100">Login</button> </div>
                </div>
                <div class="success-data" v-else>
                    <div class="text-center d-flex flex-column"> <i class='bx bxs-badge-check'></i> <span class="text-center fs-1">You have been logged in <br> Successfully</span> </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
var app = new Vue({
	el: '#formvalidation',
	data: function () {
		return {
			email : "",
			emailBlured : false,
			valid : false,
			submitted : false,
			password:"",
			passwordBlured:false
		}
	},

	methods:{

		validate : function(){
			this.emailBlured = true;
			this.passwordBlured = true;
			if( this.validEmail(this.email) && this.validPassword(this.password)){
				this.valid = true;
			}
		},

		validEmail : function(email) {

			var re = /(.+)@(.+){2,}\.(.+){2,}/;
			if(re.test(email.toLowerCase())){
				return true;
			}

		},

		validPassword : function(password) {
			if (password.length > 7) {
				return true;
			}
		},

		submit : function(){
			this.validate();
			if(this.valid){
				this.submitted = true;
			}
		}
	}
});
</script>
<style>
body {
    background: #dddddd
}
.card {
    border: none;
}
.forms-inputs {
    position: relative
}
.forms-inputs span {
    position: absolute;
    top: -18px;
    left: 10px;
    background-color: #fff;
    padding: 5px 10px;
    font-size: 15px
}
.forms-inputs input {
    height: 50px;
    border: 2px solid #eee
}
.forms-inputs input:focus {
    box-shadow: none;
    outline: none;
    border: 2px solid #000
}
.btn {
    height: 50px
}
.success-data {
    display: flex;
    flex-direction: column
}
.bxs-badge-check {
    font-size: 90px
}
</style>
</body>
</html>

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>

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>

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

?>

Vue.js PHP Input Validation

Vue.js PHP Input Validation

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

?>

Tuesday, February 1, 2022

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

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

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

https://bootstrap-vue.org/

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

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

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

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

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

ALTER TABLE `vueuser`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
index.php
//index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<title>Vuejs PHP OOP PDO Mysql CRUD (Create, Read, Update and Delete)</title>
<style>
[v-cloak] {
    display: none;
}
</style>
</head>
<body class="bg-light">
    <div class="container" id="app" v-cloak>
        <div class="row">
            <div class="col-md-10"><h3>Vuejs PHP OOP PDO Mysql CRUD (Create, Read, Update and Delete)</h3>
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex d-flex justify-content-between">
                            <div class="lead">PHP PDO VUEJS CRUD</div>
                            <button id="show-btn" @click="showModal('my-modal')" class="btn btn-primary">Add Records</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="text-muted lead text-center" v-if="!records.length">No record found</div>
                        <div class="table table-success table-striped" v-if="records.length">
                            <table class="table table-borderless">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Email</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="(record, i) in records" :key="record.id">
                                        <td>{{i + 1}}</td>
                                        <td>{{record.name}}</td>
                                        <td>{{record.email}}</td>
                                        <td>
                                            <a href="#" @click.prevent="deleteRecord(record.id)" class="btn btn-danger">Delete</a>
                                            <a href="#" @click.prevent="editRecord(record.id)" class="btn btn-primary">Edit</a>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

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

    </div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<!-- BootstrapVue js -->
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<!-- Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
app.js
//app.js
var app = new Vue({
    el: "#app",
    data: {
        name: "",
        email: "",
        records: [],
        edit_id: "",
        edit_name: "",
        edit_email: "",
    },

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

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

                fd.append("name", this.name);
                fd.append("email", this.email);

                axios({
                    url: "insert.php",
                    method: "post",
                    data: fd,
                })
                    .then((res) => {
                        if (res.data.res == "success") {
                            app.makeToast("Success", "Record Added", "default");

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

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

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

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

                fd.append("id", id);

                axios({
                    url: "delete.php",
                    method: "post",
                    data: fd,
                })
                    .then((res) => {
                        if (res.data.res == "success") {
                            app.makeToast("Success", "Record delete successfully", "default");
                            app.getRecords();
                        } else {
                            app.makeToast("Error", "Failed to delete record. Please try again", "default");
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }
        },

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

            fd.append("id", id);

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

        onUpdate() {
            if (
                this.edit_name !== "" &&
                this.edit_email !== "" &&
                this.edit_id !== ""
            ) {
                var fd = new FormData();

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

                axios({
                    url: "update.php",
                    method: "post",
                    data: fd,
                })
                    .then((res) => {
                        if (res.data.res == "success") {
                            app.makeToast("Sucess", "Record update successfully", "default");

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

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

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

    mounted: function () {
        this.getRecords();
    },
});
model.php
//model.php
<?php
class Model
{
	private $server = 'localhost';
	private $username = 'root';
	private $password = '';
	private $db = 'testingdb';
	private $conn;

	public function __construct()
	{
		try {
			$this->conn = new PDO("mysql:host=$this->server;dbname=$this->db", $this->username, $this->password);
		} catch (PDOException $e) {
			echo "Connection failed: " . $e->getMessage();
		}
	}

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

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

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

		return $data;
	}

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

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

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

		return $data;
	}

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

	$model = new Model();

	$rows = $model->findAll();

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

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

		include 'model.php';

		$model = new Model();

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

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

		include 'model.php';

		$model = new Model();

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

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

		include 'model.php';

		$model = new Model();

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

		echo json_encode($data);
	}
 ?>
 
delete.php
//delete.php
<?php 

	if (isset($_POST['id'])) {
		$id = $_POST['id'];

		include 'model.php';

		$model = new Model();

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

		echo json_encode($data);
	}

Friday, January 28, 2022

Vue CLI Install Create project and run

Vue CLI Install Create project and run

Download and install Node.js and NPM Package in your system

https://nodejs.org/en/download/
https://docs.npmjs.com/cli/v8/configuring-npm/install

check the node and npm is installed

node js:
$ node -v

version of npm
$ npm -v

Check Vue JS Verison
$ vue --version
$ vue -V

Install the Vue CLI 

https://cli.vuejs.org/

https://cli.vuejs.org/guide/installation.html

$ npm install -g @vue/cli

create a project in Vue Cli 

$ vue create my-vue-app

cd my-vue-app
$ npm run serve


Tuesday, January 25, 2022

Python Flask Vuejs CRUD (Create, Read, Update and Delete) with Mysql

Python Flask Vuejs CRUD (Create, Read, Update and Delete) with Mysql


https://bootstrap-vue.org/

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

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

Install Flask-CORS extension https://flask-cors.readthedocs.io/

$ pip install -U flask-cors
from flask_cors import CORS

https://github.com/axios/axios

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

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(40, 'Brielle', 'Williamson', 'New York'),
(54, 'Bruno', 'Nash', 'London'),
(55, 'Caesar', 'Vance', 'New York'),
(56, 'Cara', 'Stevens', 'New York'),
(57, 'Cedric', 'Kelly', 'Edinburgh'),
(58, 'Zorita Serran', 'Satou', 'Tokyo'),
(59, 'Angelica ', 'Ramos', 'London'),
(60, 'Ashton ', 'Cox', 'San Francisco'),
(61, 'Bradley ', 'Greer', 'London'),
(62, 'Brenden ', 'Wagner', 'San Francisco'),
(63, 'Brielle', 'Williamson', 'New York'),
(64, 'Bruno', 'Nash', 'London'),
(65, 'Caesar', 'Vance', 'New York'),
(66, 'Cara', 'Stevens', 'New York'),
(67, 'Brenden ', 'Wagner', 'San Francisco'),
(68, 'Brielle', 'Williamson', 'New York'),
(69, 'Bruno', 'Nash', 'London'),
(70, 'Caesar', 'Vance', 'New York'),
(71, 'Cara', 'Stevens', 'New York'),
(72, 'Cedric', 'Kelly', 'Edinburgh');

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=73;
crud.html
//crud.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<title>Python Flask Vuejs CRUD (Create, Read, Update and Delete) with PHP Mysql</title>
</head>
<body>
<div class="container" id="vuejscrudapp">
	<div class="row">
        <div class="col-md-12 mt-5">
          <h1 class="text-center">Python Flask Vuejs CRUD (Create, Read, Update and Delete) with PHP Mysql</h1>
          <hr>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
          <!-- Add Records -->
        <div>
            <b-button id="show-btn" @click="showModal('my-modal')">Add Records</b-button>
 
            <b-modal ref="my-modal" hide-footer title="Add Records">
              <div>
                <form action="" @submit.prevent="onSubmit">
                  <div class="form-group">
                    <label for="">First Name</label>
                    <input type="text" v-model="firstname" class="form-control">
                  </div>
                  <div class="form-group">
                    <label for="">Last Name</label>
                    <input type="text" v-model="lastname" class="form-control">
                  </div>
				  <div class="form-group">
                    <label for="">Address</label>
                    <input type="text" v-model="address" class="form-control">
                  </div>
                  <div class="form-group">
                    <button class="btn btn-sm btn-outline-info">Add Records</button>
                  </div>
                </form>
              </div>
              <b-button class="mt-3" variant="outline-danger" block @click="hideModal('my-modal')">Close Me</b-button>
            </b-modal>
        </div>
 
        <!-- Update Record -->
        <div>
            <b-modal ref="my-modal1" hide-footer title="Update Record">
              <div>
                <form action="" @submit.prevent="onUpdate">
                  <div class="form-group">
                    <label for="">First Name</label>
                    <input type="text" v-model="edit_id">
                    <input type="text" v-model="edit_firstname" class="form-control">
                  </div>
                  <div class="form-group">
                    <label for="">Last Name</label>
                    <input type="text" v-model="edit_lastname" class="form-control">
                  </div>
				  <div class="form-group">
                    <label for="">Address</label>
                    <input type="text" v-model="edit_address" class="form-control">
                  </div>
                  <div class="form-group">
                    <button class="btn btn-sm btn-outline-info">Update Record</button>
                  </div>
                </form>
              </div>
              <b-button class="mt-3" variant="outline-danger" block @click="hideModal('my-modal1')">Close Me</b-button>
            </b-modal>
          </div>
		  
        </div>
	</div>
	  
    <div class="row">
        <div class="col-md-12">
          <table class="table table-striped table-bordered">
            <thead>
              <tr>
                <th>ID</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Address</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(record, i) in records" :key="record.id">
                <td>{{i + 1}}</td>
                <td>{{record.firstname}}</td>
                <td>{{record.lastname}}</td>
                <td>{{record.address}}</td>
                <td>
                  <button @click="deleteRecord(record.id)" class="btn btn-sm btn-outline-danger">Delete</button>
                  <button @click="editRecord(record.id)" class="btn btn-sm btn-outline-info">Edit</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
    </div>
</div>
 
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<!-- BootstrapVue js -->
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<!-- Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    var app = new Vue({
        el: '#vuejscrudapp',
        data: {
			firstname: '',
			lastname: '',
			address: '',
			records: [],
			edit_id: '',
			edit_firstname: '',
			edit_lastname: '',
			edit_address: ''
        },
 
        methods: {
			showModal(id) {
				this.$refs[id].show()
			},
			hideModal(id) {
				this.$refs[id].hide()
			},
 
			onSubmit(){
				if (this.firstname !== '' && this.lastname !== '' && this.address !== '') {
					var config = { headers: {  
						'Content-Type': 'application/json',
						'Access-Control-Allow-Origin': '*'}
					}
					axios.post("http://127.0.0.1:5000/insert", 
						{ firstname : this.firstname, lastname : this.lastname, address : this.address}, config
					)
					.then(res => {
						console.log(res)
						alert('New record Successfully added')
						this.firstname = ''
						this.lastname = ''
						this.address = ''
		 
						app.hideModal('my-modal')
						app.getRecords()
					})
					.catch(err => {
						console.log(err)
					})
				}else{
				  alert('empty')
				}
			},
 
			getRecords(){
				axios({
				  url: 'http://localhost:5000/',
				  method: 'get'
				})
				.then(res => {
				  console.log(res)
				  this.records = res.data.members
				})
				.catch(err => {
				  console.log(err)
				})
			},
 
			editRecord(id){
				axios.get("http://127.0.0.1:5000/edit/" + id)
				.then(res => {
					console.log(res.data)
				    this.edit_id = res.data.editmember['id']
				    this.edit_firstname = res.data.editmember['firstname']
				    this.edit_lastname = res.data.editmember['lastname']
				    this.edit_address = res.data.editmember['address']
					app.showModal('my-modal1')
				})
				.catch(err => {
				  console.log(err)
				})
			},
			
			onUpdate(){
				if (this.edit_firstname !== '' && this.edit_lastname !== '' && this.edit_address !== '' && this.edit_id !== '') {

				    var config = { headers: {  
						'Content-Type': 'application/json',
						'Access-Control-Allow-Origin': '*'}
					}
					axios.post("http://127.0.0.1:5000/update", 
						{ edit_id : this.edit_id, edit_firstname : this.edit_firstname, edit_lastname : this.edit_lastname, edit_address : this.edit_address}, config
					)
					.then(res => {
						console.log(res)
						alert('record update');
		 
						this.edit_firstname = '';
						this.edit_lastname = '';
						this.edit_address = '';
						this.edit_id = '';
		 
						app.hideModal('my-modal1');
						app.getRecords();
					})
					  .catch(err => {
						console.log(err)
					})
	 
				}else{
				  alert('empty')
				}
			},
			
			deleteRecord(id){
				if (window.confirm('Delete this record')) {
					axios.get("http://127.0.0.1:5000/delete/" + id)
					.then(res => {
						console.log(res)
						alert('delete successfully')
						app.getRecords();
					})
					.catch(err => {
						console.log(err)
					})
				}
			},
		
        },
		  
        mounted: function(){
          this.getRecords()
        }
    })
</script>
</body>   
</html>
app.py
//app.py
from flask import Flask, jsonify, request
from flask_cors import CORS
from flaskext.mysql import MySQL #pip install flask-mysql
import pymysql

MEMBERS = [
    {
        'id': '1',
        'firstname': 'cairocoders',
        'lastname': 'Ednalan',
        'address': 'Olongapo city'
    },
    {
        'id': '2',
        'firstname': 'clydey',
        'lastname': 'Ednalan',
        'address': 'Angles city'
    }
]
# configuration
DEBUG = True

# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)
    
mysql = MySQL()
   
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'testingdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})


# sanity check route
@app.route('/ping', methods=['GET'])
def ping_pong():
    return jsonify('pong!')

@app.route('/members', methods=['GET'])
def all_members():
    return jsonify({
        'status': 'success',
        'members': MEMBERS
    })

@app.route('/')
def home():
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    try:
        cursor.execute("SELECT * from members order by id")
        userslist = cursor.fetchall()
        return jsonify({
            'status': 'success',
            'members': userslist
        })
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()

@app.route('/insert', methods=['GET', 'POST'])
def insert():
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    response_object = {'status': 'success'}
    if request.method == 'POST':
        post_data = request.get_json(silent=True)
        firstname = post_data.get('firstname')
        lastname = post_data.get('lastname')
        address = post_data.get('address')

        print(firstname)
        print(lastname)

        sql = "INSERT INTO members(firstname,lastname,address) VALUES(%s, %s, %s)"
        data = (firstname, lastname, address)
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute(sql, data)
        conn.commit()

        response_object['message'] = "Successfully Added"
    return jsonify(response_object)

@app.route('/edit/<string:id>', methods=['GET', 'POST'])
def edit(id):
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    print(id)
    cursor.execute("SELECT * FROM members WHERE id = %s", [id])
    row = cursor.fetchone() 

    return jsonify({
        'status': 'success',
        'editmember': row
    })

@app.route('/update', methods=['GET', 'POST'])
def update():
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    response_object = {'status': 'success'}
    if request.method == 'POST':
        post_data = request.get_json(silent=True)
        edit_id = post_data.get('edit_id')
        edit_firstname = post_data.get('edit_firstname')
        edit_lastname = post_data.get('edit_lastname')
        edit_address = post_data.get('edit_address')

        print(edit_firstname)
        print(edit_lastname)

        cursor.execute ("UPDATE members SET firstname=%s, lastname=%s, address=%s WHERE id=%s",(edit_firstname, edit_lastname, edit_address, edit_id))
        conn.commit()
        cursor.close()

        response_object['message'] = "Successfully Updated"
    return jsonify(response_object)

@app.route('/delete/<string:id>', methods=['GET', 'POST'])
def delete(id):
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
  
    response_object = {'status': 'success'}

    cursor.execute("DELETE FROM members WHERE id = %s", [id])
    conn.commit()
    cursor.close()
    response_object['message'] = "Successfully Deleted"
    return jsonify(response_object)

if __name__ == '__main__':
    app.run()

Related Post