article

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

Sunday, January 23, 2022

Python Flask Vue.js fetchAll Data from Mysql Database

Python Flask Vue.js fetchAll Data from Mysql Database

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

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;


index.html
//index.html
<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Python Flask Vue.js fetchAll Data from Mysql Database</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
  <div class="container" id="fetchAlldiv">
   <br />
   <h3 align="center">Python Flask Vue.js fetchAll Data from Mysql Database</h3>
   <br />

   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
       <h3 class="panel-title"> Member List</h3>
     </div>
    </div>
    <div class="panel-body">
        <div class="table-responsive">
          <table class="table table-bordered table-striped">
           <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Address</th>
            <th>Edit</th>
            <th>Delete</th>
           </tr>
           <tr v-for="rs in allData">
			  <td>{{ rs.firstname }}</td>
              <td>{{ rs.lastname }}</td>
              <td>{{ rs.address }}</td>
            <td><button type="button" name="edit" class="btn btn-primary btn-xs edit">Edit</button></td>
            <td><button type="button" name="delete" class="btn btn-danger btn-xs delete">Delete</button></td>
           </tr>
          </table>
        </div>
    </div>
   </div>
</div>
<script>
var application = new Vue({
    el:'#fetchAlldiv',
    data:{
        allData:'',
    },
    methods:{
        fetchAllData:function(){ //show records
           axios.get('http://localhost:5000/')
		   .then(function(response){
				console.log(response);
				application.allData = response.data.members;
           });
        }
    }, 
    created:function(){
      this.fetchAllData();
    }
});
</script>
</body>
</html>
app.py
//app.py
from flask import Flask, jsonify
from flask_cors import CORS
from flaskext.mysql import MySQL #pip install flask-mysql
import pymysql

# 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': '*'}})

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

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

Tuesday, January 11, 2022

Python Flask Vue.js Axios - List All Data

Python Flask Vue.js Axios - List All Data

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

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

We'll be using the Vue CLI  https://cli.vuejs.org/

$ vue create client
This will require you to answer a few questions about the project.

Vue CLI v4.5.11
? Please pick a preset: (Use arrow keys)
❯ Default ([Vue 2] babel, eslint)
  Default (Vue 3 Preview) ([Vue 3] babel, eslint)
  Manually select features

Use the down arrow key to highlight

Run development server:
$ cd client
$ npm run serve

Install Bootstrap https://getbootstrap.com/docs/5.0/getting-started/download/
$ npm install bootstrap

Install Axios
https://github.com/axios/axios
$ npm install axios
app.py
 
from flask import Flask, jsonify
from flask_cors import CORS

MEMBERS = [
    {
        'id': '1',
        'name': 'cairocoders Ednalan',
        'email': 'cairocoders@gmail.com',
        'address': 'Olongapo city'
    },
    {
        'id': '2',
        'name': 'clydey Ednalan',
        'email': 'clydey@gmail.com',
        'address': 'Angles city'
    },
    {
        'id': '3',
        'name': 'claydren Ednalan',
        'email': 'clyderen@gmail.com',
        'address': 'San Fernando city'
    }
]

# configuration
DEBUG = True

# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)

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

if __name__ == '__main__':
    app.run()
client/scr/main.js
//client/scr/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router';
import 'bootstrap/dist/css/bootstrap.css';

Vue.config.productionTip = false

new Vue({
  router,
  render: (h) => h(App),
}).$mount('#app');
client/src/App.vue
//client/src/App.vue
<template>
  <div id="app">
    <router-view/>
  </div>
</template>
client/src/Ping.vue
//client/src/Ping.vue
<template>
  <div>
    <p>{{ msg }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Ping',
  data() {
    return {
      msg: '',
    };
  },
  methods: {
    getMessage() {
      const path = 'http://localhost:5000/ping';
      axios.get(path)
        .then((res) => {
          console.log(res)
          this.msg = res.data;
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
  created() {
    this.getMessage();
  },
};
</script>
client/src/components/Home.vue
//client/src/components/Home.vue
<template>
  <div class="container">
    <div class="row">
      <div class="col-sm-10">
        <h1>Member</h1>
        <hr><br><br>
        <button type="button" class="btn btn-success btn-sm">Add Member</button>
        <br><br>
        <table class="table table-hover">
          <thead>
            <tr>
              <th scope="col">Name</th>
              <th scope="col">Email</th>
              <th scope="col">Address</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(rs, index) in members" :key="index">
              <td>{{ rs.name }}</td>
              <td>{{ rs.email }}</td>
              <td>{{ rs.address }}</td>
              <td>
                <div class="btn-group" role="group">
                  <button type="button" class="btn btn-warning btn-sm">Update</button>
                  <button type="button" class="btn btn-danger btn-sm">Delete</button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      members: [],
    };
  },
  methods: {
    getMembers() {
      const path = 'http://localhost:5000/members';
      axios.get(path)
        .then((res) => {
          console.log(res);
          this.members = res.data.members;
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
  created() {
    this.getMembers();
  },
};
</script>
client/src/router/index.js
//client/src/router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Ping from '../components/Ping.vue';
import Home from '../components/Home.vue';

Vue.use(Router);

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },
    {
      path: '/ping',
      name: 'Ping',
      component: Ping,
    },
  ],
});

Sunday, January 2, 2022

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

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

Download or Include 

https://bootstrap-vue.org/

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

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

CREATE TABLE `member` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

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

ALTER TABLE `member`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

//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 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>Vuejs PHP Mysqli OOP CRUD (Create, Read, Update and Delete)</title>

    <style>
      [v-cloak] {
        display: none;
      }
    </style>

  </head>
  <body>
    <div class="container" id="vuejscrudapp" v-cloak>
      <div class="row">
        <div class="col-md-12 mt-5">
          <h1 class="text-center">Vuejs PHP Mysqli OOP CRUD (Create, Read, Update and Delete)</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="">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>
              </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="">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 class="row" v-if="records.length">
        <div class="col-md-12">
          <table class="table table-striped table-bordered">
            <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>
                  <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: {
          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 => {
                // console.log(res)
                if (res.data.res == 'success') {
                  alert('record added')
                  this.name = ''
                  this.email = ''

                  app.hideModal('my-modal')
                  app.getRecords()
                }else{
                  alert('error')
                }
              })
              .catch(err => {
                console.log(err)
              })
            }else{
              alert('empty')
            }
          },

          getRecords(){
            axios({
              url: 'records.php',
              method: 'get'
            })
            .then(res => {
              // console.log(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 => {
                // console.log(res)
                if (res.data.res == 'success') {
                  alert('delete successfully')
                  app.getRecords();
                }else{
                  alert('error')
                }
              })
              .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 => {
                // console.log(res)
                if (res.data.res == 'success') {
                  alert('record update');

                  this.edit_name = '';
                  this.edit_email = '';
                  this.edit_id = '';

                  app.hideModal('my-modal1');
                  app.getRecords();
                }
              })
              .catch(err => {
                console.log(err)
              })

            }else{
              alert('empty')
            }
          }

        },

        mounted: function(){
          this.getRecords()
        }
      })
</script>
</body>	
</html>
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 mysqli($this->server, $this->username, $this->password, $this->db);
			} catch (Exception $e) {
				echo "Connection error " . $e->getMessage();
			}
		}

		public function insert($name, $email){
			$query = "INSERT INTO member (`name`, `email`) VALUES ('$name', '$email')";
			if ($sql = $this->conn->query($query)) {
				return true;
			}else{
				return;
			}
		}

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

			$query = "SELECT * FROM member";

			if ($sql = $this->conn->query($query)) {
				while ($rows = mysqli_fetch_assoc($sql)) {
					$data[] = $rows;
				}
			}

			return $data;
		}

		public function delete($id){
			$query = "DELETE FROM member WHERE `id` = '$id'";
			if ($sql = $this->conn->query($query)) {
				return true;
			}else{
				return;
			}
		}

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

			$query = "SELECT * FROM member WHERE `id` = '$id'";
			if ($sql = $this->conn->query($query)) {
				$row = mysqli_fetch_row($sql);
				$data = $row;
			}

			return $data;
		}

		public function update($id, $name, $email){
			$query = "UPDATE member SET `name` = '$name', `email` = '$email' WHERE `id` = '$id'";
			if ($sql = $this->conn->query($query)) {
				return true;
			}else{
				return;
			}
		}
	}

 ?>
 
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->insert($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->edit($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->delete($id)) {
			$data = array('res' => 'success');
		}else{
			$data = array('res' => 'error');
		}

		echo json_encode($data);
	}
 ?>
 
records.php
//records.php
<?php 
	include 'model.php';

	$model = new Model();

	$rows = $model->fetch();

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

	echo json_encode($data);
 ?>
 

Friday, December 3, 2021

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

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

https://vue-select.org/

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

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

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

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

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

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

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

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

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

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

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

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

echo json_encode($response_arr);
exit;

Monday, November 22, 2021

Vue.js Axios Dynamic Dependent Select Box with PHP and Mysql

Vue.js Axios Dynamic Dependent Select Box with PHP and Mysql

Download or Include 

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

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


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


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

ALTER TABLE `country`
  MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;


CREATE TABLE `state` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `country_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

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

ALTER TABLE `state`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;

CREATE TABLE `city` (
  `id` int(11) NOT NULL,
  `cityname` varchar(150) NOT NULL,
  `stateid` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `city` (`id`, `cityname`, `stateid`) VALUES
(1, 'Anaheim', 8),
(2, 'Arden-Arcade', 8),
(3, 'Bakersfield', 8),
(4, 'Carson', 8),
(5, 'Daly City', 8),
(6, 'Angeles City', 3),
(7, 'Olongapo', 3),
(8, 'San Fernando', 3),
(9, 'Tarlac', 3);

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

ALTER TABLE `city`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vue.js Axios Dynamic Dependent Select Box with PHP and Mysql</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<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 class="container" id="dynamicselectboxApp">
		<h3 align="center">Vue.js Axios Dynamic Dependent Select Box with PHP and Mysql</h3>
		<br />
		<div class="panel panel-default">
			<div class="panel-heading">Dynamic Dependent Select Box</div>
			<div class="panel-body">
				<div class="form-group">
					<label>Select Country</label>
					<select class="form-control input-lg" v-model="selcountry" @change="fetchState">
					   <option value="">Select Country</option>
					   <option v-for="data in country_data" :value="data.id">{{ data.country }}</option>
					</select>
				</div>
				
				<div class="form-group">
					<label>Select State</label>
					<select class="form-control input-lg" v-model="selstate" @change="fetchCity">
					   <option value="">Select state</option>
					   <option v-for="data in state_data" :value="data.id">{{ data.name }}</option>
					</select>
				</div>
				
				<div class="form-group">
					<label>Select City</label>
					<select class="form-control input-lg" v-model="selcity">
					   <option value="">Select City</option>
					   <option v-for="data in city_data" :value="data.id">{{ data.cityname }}</option>
					</select>
				</div>
			</div>
		</div>
	</div>
	
<script>
var app = new Vue({
	el:'#dynamicselectboxApp',
	data:{
		selcountry:'',
		country_data:'',
		selstate:'',
		state_data:'',
		selcity:'',
		city_data:''
	},
	
	methods:{
		fetchCountry:function(){
		   axios.post("action.php", {
			postRequest:'country'
		   }).then(function(response){
			app.country_data = response.data;
			app.selstate = '';
			app.state_data = '';
			app.selcity = '';
			app.city_data = '';
		   });
		},
		  
		fetchState:function(){
		   axios.post("action.php", {
			postRequest:'state',
			country_id:this.selcountry
		   }).then(function(response){
			app.state_data = response.data;
			app.selstate = '';
			app.selcity = '';
			app.city_data = '';
		   });
		},
		
		fetchCity:function(){
		   axios.post("action.php", {
			postRequest:'city', 
			state_id:this.selstate
		   }).then(function(response){
			app.city_data = response.data;
			app.selcity = '';
		   });
		}
	},
 
	created:function(){
	  this.fetchCountry();
	}
});
</script>
 </body>
</html>
action.php
//action.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");

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

if($received_data->postRequest == 'country')
{
	$query = "SELECT * FROM country ORDER BY country ASC";
}

if($received_data->postRequest == 'state')
{
	$query = "SELECT * FROM state WHERE country_id = '".$received_data->country_id."' ORDER BY name ASC";
}

if($received_data->postRequest == 'city')
{
	$query = "SELECT * FROM city WHERE stateid = '".$received_data->state_id."' ORDER BY cityname ASC";
} 

$statement = $connect->prepare($query);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
	$data[] = $row;
}
echo json_encode($data);
?>

Sunday, November 21, 2021

Vue.Js Multi Step Form

Vue.Js Multi Step Form

index.html
//index.html
<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Vue.Js Multi Step Form</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/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">
	<h1 class="page-header text-center">Vue.Js Multi Step Form</h1>
	<div id="app">
		<template id="user_detail1" v-if="activePhase == 1">
			<h1>Step 1</h1>
			<div class="form-group col">
				<label>Name</label><input name="name" v-model="user_detail1.name" placeholder="name" class="form-control">
			</div>
			<div class="form-group col">
				<label>Email</label><input name="email" v-model="user_detail1.email" placeholder="email" class="form-control">
			</div>
			<button type="button" @click.prevent="goToStep(2)" class="btn btn-primary">Continue</button>
		</template>
		
		<template id="user_detail2" v-if="activePhase == 2">
			<h1>Step 2</h1>
			<div class="form-group col">
				<label>City</label><input name="city" v-model="user_detail2.city" placeholder="city" class="form-control">
			</div>
			<div class="form-group col">
				<label>State</label><input name="state" v-model="user_detail2.state" placeholder="state" class="form-control">
			</div>
			<button type="button" @click.prevent="goToStep(3)" class="btn btn-primary">Finish</button>
		</template>
		
		<template id="step3" v-if="activePhase == 3">
			<strong>Name:</strong> {{ user_detail1.name }}<br />
			<strong>Email:</strong> {{ user_detail1.email }}<br />
			<strong>City:</strong> {{ user_detail2.city }}<br />
			<strong>State:</strong> {{ user_detail2.state }}
		</template>
	</div>
</div>
<script>
Vue.component('user_detail1', {
    template: '#user_detail1',
    props: [
        'activePhase',
        'user_detail1'
    ]
});

Vue.component('user_detail2', {
    template: '#user_detail2',
    props: [
        'activePhase',
        'user_detail2'
    ]
});

Vue.component('step3', {
    template: '#step3',
    props: [
        'activePhase',
        'user_detail1',
        'user_detail2'
    ]
});

var app = new Vue({
    el: '#app',
    data: {
        activePhase: 1,
        user_detail1: {
            name: '',
            email: ''
        },
        user_detail2: {
            city: '',
            state: ''
        }
    },
    ready: function() {
        console.log('ready');
    },
    methods: {
        goToStep: function(step) {
            this.activePhase = step;
        }
    }
});
</script>
</body>
</html>

Friday, November 19, 2021

Vue.js Axios upload file with PHP

Vue.js Axios upload file with PHP

Download or Include 

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js
index.html
//index.html
<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Vue.js Axios upload file with PHP</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <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 class="container" id="vuejsuploadapp">
	   <br />
	   <h3 align="center">Vue.js Axios upload file with PHP</h3>
	   <br />
	   <div v-if="successAlert" class="alert alert-success alert-dismissible">
		  <a href="#" class="close" aria-label="close" @click="successAlert=false">×</a>
		  {{ successMessage }}
	   </div>

	   <div v-if="errorAlert" class="alert alert-danger alert-dismissible">
		  <a href="#" class="close" aria-label="close" @click="errorAlert=false">×</a>
		  {{ errorMessage }}
	   </div>
	   
	    <div class="panel panel-default">
			<div class="panel-heading">
				<div class="row">
				  <div class="col-md-6">
				   <h3 class="panel-title">Upload File</h3>
				  </div>
				  <div class="col-md-6" align="right"></div>
				</div>
			</div>
			<div class="panel-body">
				<div class="row">
				  <div class="col-md-4" align="right">
				   <label>Select Image</label>
				  </div>
				  <div class="col-md-4">
				   <input type="file" ref="file" />
				  </div>
				  <div class="col-md-4">
				   <button type="button" @click="btnUpload" class="btn btn-success">Upload Image</button>
				  </div>
				</div>
			 <br />
			 <br />
			 <div v-html="uploadedImage" align="center"></div>
			</div>
	    </div>
  </div>
<script>
var application = new Vue({
	 el:'#vuejsuploadapp',
	 data:{
		file:'',
		successAlert:false,
		errorAlert:false,
		uploadedImage:'',
	 },
	 methods:{
	    btnUpload:function(){
			application.file = application.$refs.file.files[0];

			var formData = new FormData();

			formData.append('file', application.file);

			axios.post('upload.php', formData, {
				header:{
					'Content-Type' : 'multipart/form-data'
				}
			}).then(function(response){
				if(response.data.image == '') {
					 application.errorAlert = true;
					 application.successAlert = false;
					 application.errorMessage = response.data.message;
					 application.successMessage = '';
					 application.uploadedImage = '';
				}else{
				 application.errorAlert = false;
					 application.successAlert = true;
					 application.errorMessage = '';
					 application.successMessage = response.data.message;
					 var image_html = "<img src='"+response.data.image+"' class='img-thumbnail' width='500' />";
					 application.uploadedImage = image_html;
					 application.$refs.file.value = '';
				}
		   });
	   
	  }
	},
});
</script>
 </body>
</html>
upload.php
//upload.php
<?php
$image = '';
if(isset($_FILES['file']['name']))
{
	$image_name = $_FILES['file']['name'];
	$valid_extensions = array("jpg","jpeg","png");
	$extension = pathinfo($image_name, PATHINFO_EXTENSION);
	if(in_array($extension, $valid_extensions)){
		$upload_path = 'upload/' . time() . '.' . $extension;
		if(move_uploaded_file($_FILES['file']['tmp_name'], $upload_path)){
		   $message = 'Image Succesfully Uploaded';
		   $image = $upload_path;
		}else{
		   $message = 'There is an error while uploading image';
		}
	}else{
	  $message = 'Only .jpg, .jpeg and .png Image allowed to upload';
	}
}else{
	$message = 'Select Image';
}

$output = array(
 'message'  => $message,
 'image'   => $image
);

echo json_encode($output);
?>

Thursday, November 18, 2021

Vue.js Axios Autocomplete textbox with PHP and MySQL

Vue.js Autocomplete textbox with PHP and MySQL

Download or Include 

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js


index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<title>Vue.js Autocomplete textbox with PHP and MySQL</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" type="text/css" href="style.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='myapp' style="padding:20px;">
		<p><h1>Vue.js Autocomplete textbox with PHP and MySQL</h1></p>
		<vueauto-complete v-model="country" @input="handleInput1()"></vueauto-complete>
		<p><b>Selected Country id : {{ country }}</b> </p>
	</div>
	
	<script >
	Vue.component('vueauto-complete', {
	  	data: function () {
	    	return {
	      		searchText:'',
        		suggestiondata:[]
	    	}
	  	},
	  	template: `<div class='vueautocomplete' > 
	  		<div>
		  		<input type='text' @keyup='loadSuggestions' placeholder='Enter some text' v-model='searchText'>	<br> 
		  		<div class='suggestionlist' v-if="suggestiondata.length" >
		  		<ul> 
		  			<li v-for= '(item,index) in suggestiondata' @click='itemSelected(index)'> 
		  				{{ item.name }} 
		  			</li>  
		  		</ul>
		  		</div>  
	  		</div>
	  	</div>`, 
	  	methods: {
			loadSuggestions: function(e){
				var el = this;
				this.suggestiondata = [];
				
				if(this.searchText != ''){

					axios.get('search.php', {
						params: {
							search: this.searchText
						}
					})
					.then(function (response) {
						el.suggestiondata = response.data;
					});
				}	
			},
			itemSelected: function(index){
				var id = this.suggestiondata[index].id;	
				var name = this.suggestiondata[index].name;	

				this.searchText = name;
				this.suggestiondata = [];

				this.$emit("input", id);
			}
		},
	})

	var app = new Vue({
	  	el: '#myapp',
	  	data: {
		    country: 0
		},
		methods: {
			handleInput1: function(){
				console.log("value : " + this.country);
			}
		}
	})
	</script>
</body>
</html>
search.php
//search.php
<?php
include "config.php";

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

	$data = array();
	if(!empty($search)){

		$result = mysqli_query($con,"select * from country where country like '%".$search."%'");
		
		while ($row = mysqli_fetch_array($result)) {
		  	$data[] = array(
		  			"id" => $row['id'],
		  			"name"=>$row['country']
		  		);
		}
	}

	echo json_encode($data);
	exit;
}
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());
}
style.css
//style.css
.vueautocomplete,.vueautocomplete .suggestionlist{
    width: 300px;
}
.vueautocomplete input[type=text]{
    width: 100%;
    padding: 5px;
}
.suggestionlist{
    position: absolute;
}
.suggestionlist ul{
    width: 100%;
    background: whitesmoke;
    list-style: none;
    margin: 0;
    padding: 5px;
} 
.suggestionlist ul li{
    background: white;
    padding: 4px;
    margin-bottom: 1px;
}
.suggestionlist li:not(:last-child){
    border-bottom: 1px solid #cecece;
}
.suggestionlist ul li:hover{
    cursor: pointer;
    background: whitesmoke;
}

Saturday, November 13, 2021

Vue.js Axios Live Search using PHP Mysqli

Vue.js Axios Live Search using PHP Mysqli

Download or Include 

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

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

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

index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>Vue.js Axios Live Search using PHP Mysqli</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div id="vueappsearch">
	<div class="container">
		<h1 class="page-header text-center">Vue.js Axios Live Search using PHP Mysqli</h1>
		<div class="col-md-8 col-md-offset-2">
			<div class="row">
				<div class="col-md-4 col-md-offset-8">
					<input type="text" class="form-control" placeholder="Search Name or Position" v-on:keyup="searchMonitor" v-model="search.keyword">
				</div>
			</div>
			<div style="height:5px;"></div>
			<table class="table table-bordered table-striped">
				<thead>
					<th>Name</th>
					<th>Position</th>
					<th>Office</th>
					<th>Age</th>
					<th>Salary</th>
				</thead>
				<tbody>
					
					<tr v-if="noMember">
						<td colspan="2" align="center">No member match your search</td>
					</tr>
					
					<tr v-for="member in employee">
						<td>{{ member.name }}</td>
						<td>{{ member.position }}</td>
						<td>{{ member.office }}</td>
						<td>{{ member.age }}</td>
						<td>{{ member.salary }}</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.min.js"></script>
<script src="vuesearchapp.js"></script>
</body>
</html>
vuesearchapp.js
//vuesearchapp.js
var app = new Vue({
	el: '#vueappsearch',
	data:{
		employee: [],
		search: {keyword: ''},
		noMember: false
	},

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

	methods:{
		searchMonitor: function() {
			var keyword = app.toFormData(app.search);
	   		axios.post('action.php?action=search', keyword)
				.then(function(response){
					app.employee = response.data.employee;

					if(response.data.employee == ''){
						app.noMember = true;
					}
					else{
						app.noMember = false;
					}
				});
       	},

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

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

	}
});
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 employee";
	$query = $conn->query($sql);
	$employee = array();

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

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

if($action=='search'){
	$keyword=$_POST['keyword'];
	$sql="select * from employee where name like '%$keyword%' or position like '%$keyword%'";
	$query = $conn->query($sql);
	$employee = array();

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

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

$conn->close();

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

Vue.js Axios Login with PHP MySQLi

Vue.js Axios Login with PHP MySQLi

Download or Include 

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

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

INSERT INTO `vueuser` (`id`, `username`, `password`) VALUES
(1, 'cairocoders', '123456'),
(2, 'tutorial101.blogspot.com', '1234567');

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

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

index.php
//index.php
<?php
	session_start();
	if(isset($_SESSION['user'])){
		header('location:success.php');
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title>Vue.js Axios Login with PHP MySQLi</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">Vue.js Axios Login with PHP MySQLi</h1>
	<div id="vueapplogin">
		<div class="col-md-4 col-md-offset-4">
			<div class="panel panel-primary">
			  	<div class="panel-heading"><span class="glyphicon glyphicon-lock"></span> Sign in</div>
			  	<div class="panel-body">
			    	<label>Username:</label>
			    	<input type="text" class="form-control" v-model="logDetails.username" v-on:keyup="keymonitor">
			    	<label>Password:</label>
			    	<input type="password" class="form-control" v-model="logDetails.password" v-on:keyup="keymonitor">
			  	</div>
			  	<div class="panel-footer">
			  		<button class="btn btn-primary btn-block" @click="checkLogin();"><span class="glyphicon glyphicon-log-in"></span> Login</button>
			  	</div>
			</div>

			<div class="alert alert-danger text-center" v-if="errorMessage">
				<button type="button" class="close" @click="clearMessage();"><span aria-hidden="true">×</span></button>
				<span class="glyphicon glyphicon-alert"></span> {{ errorMessage }}
			</div>

			<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>
	</div>
</div>
<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="applogin.js"></script>
</body>
</html>
applogin.js
//applogin.js
var app = new Vue({
	el: '#vueapplogin',
	data:{
		successMessage: "",
		errorMessage: "",
		logDetails: {username: '', password: ''},
	},

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

		checkLogin: function(){
			var logForm = app.toFormData(app.logDetails);
			axios.post('login.php', logForm)
				.then(function(response){

					if(response.data.error){
						app.errorMessage = response.data.message;
					}
					else{
						app.successMessage = response.data.message;
						app.logDetails = {username: '', password:''};
						setTimeout(function(){
							window.location.href="success.php";
						},2000);
						
					}
				});
		},

		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.errorMessage = '';
			app.successMessage = '';
		}

	}
});
login.php
//login.php
<?php
session_start();
include('dbcon.php');

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

$username = $_POST['username'];
$password = $_POST['password'];

if($username==''){
	$out['error'] = true;
	$out['message'] = "Username is required";
}
else if($password==''){
	$out['error'] = true;
	$out['message'] = "Password is required";
}
else{
	$sql = "select * from vueuser where username='$username' and password='$password'";
	$query = $conn->query($sql);

	if($query->num_rows>0){
		$row=$query->fetch_array();
		$_SESSION['user']=$row['id'];
		$out['message'] = "Login Successful";
	}
	else{
		$out['error'] = true;
		$out['message'] = "Login Failed. User not Found";
	}
}
	
$conn->close();

header("Content-type: application/json");
echo json_encode($out);
die();
?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
success.php
//success.php
<?php
	session_start();
	include('dbcon.php');

	if (!isset($_SESSION['user']) ||(trim ($_SESSION['user']) == '')){
		header('location:index.php');
	}

	$sql="select * from vueuser where id='".$_SESSION['user']."'";
	$query=$conn->query($sql);
	$row=$query->fetch_array();

?>
<!DOCTYPE html>
<html>
<head>
	<title>Vue.js Axios Login with PHP MySQLi</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
	<div class="container">
		<div class="jumbotron">
			<h1 class="text-center">Welcome, <?php echo $row['username']; ?>!</h1>
			<a href="logout.php" class="btn btn-primary"><span class="glyphicon glyphicon-log-out"></span> Logout</a>
		</div>
	</div>
</body>
</html>
logout.php
//logout.php
<?php
	session_start();
	session_destroy();
	header('location:index.php');
?>

Vue.js Axios CRUD (Create, Read, Update and Delete) using PHP MySQLi

Vue.js Axios CRUD (Create, Read, Update and Delete) using PHP MySQLi

Download or Include 

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

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

INSERT INTO `members` (`memid`, `firstname`, `lastname`) VALUES
(2, 'Airi', 'Satou'),
(3, 'Angelica', 'Ramos'),
(4, 'Ashton', 'Cox'),
(5, 'Bradley', 'Greer'),
(6, 'Brenden', 'Wagner');

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

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

index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>Vue.js Axios CRUD (Create, Read, Update and Delete) using PHP MySQLi</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">Vue.js Axios CRUD (Create, Read, Update and Delete) using PHP MySQLi</h1>
	<div id="vuejscrudmembers">
		<div class="col-md-8 col-md-offset-2">
			<div class="row">
				<div class="col-md-12">
					<h2>Member List
					<button class="btn btn-primary pull-right" @click="showAddModal = true"><span class="glyphicon glyphicon-plus"></span> Member</button>
					</h2>
				</div>
			</div>

			<div class="alert alert-danger text-center" v-if="errorMessage">
				<button type="button" class="close" @click="clearMessage();"><span aria-hidden="true">×</span></button>
				<span class="glyphicon glyphicon-alert"></span> {{ errorMessage }}
			</div>
			
			<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-ok"></span> {{ successMessage }}
			</div>

			<table class="table table-bordered table-striped">
				<thead>
					<th>Firstname</th>
					<th>Lastname</th>
					<th>Action</th>
				</thead>
				<tbody>
					<tr v-for="member in members">
						<td>{{ member.firstname }}</td>
						<td>{{ member.lastname }}</td>
						<td>
							<button class="btn btn-success" @click="showEditModal = true; selectMember(member);"><span class="glyphicon glyphicon-edit"></span> Edit</button> 
							<button class="btn btn-danger" @click="showDeleteModal = true; selectMember(member);"><span class="glyphicon glyphicon-trash"></span> Delete</button>
						</td>
					</tr>
				</tbody>
			</table>
		</div>
		<?php include('modal.php'); ?>
	</div>
</div>
<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="app.js"></script>
</body>
</html>
app.js
//app.js
var app = new Vue({
	el: '#vuejscrudmembers',
	data:{
		showAddModal: false,
		showEditModal: false,
		showDeleteModal: false,
		errorMessage: "",
		successMessage: "",
		members: [],
		newMember: {firstname: '', lastname: ''},
		clickMember: {}
	},

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

	methods:{
		getAllMembers: function(){
			axios.get('api.php')
				.then(function(response){
					//console.log(response);
					if(response.data.error){
						app.errorMessage = response.data.message;
					}
					else{
						app.members = response.data.members;
					}
				});
		},

		saveMember: function(){
			//console.log(app.newMember);
			var memForm = app.toFormData(app.newMember);
			axios.post('api.php?crud=create', memForm)
				.then(function(response){
					//console.log(response);
					app.newMember = {firstname: '', lastname:''};
					if(response.data.error){
						app.errorMessage = response.data.message;
					}
					else{
						app.successMessage = response.data.message
						app.getAllMembers();
					}
				});
		},

		updateMember(){
			var memForm = app.toFormData(app.clickMember);
			axios.post('api.php?crud=update', memForm)
				.then(function(response){
					//console.log(response);
					app.clickMember = {};
					if(response.data.error){
						app.errorMessage = response.data.message;
					}
					else{
						app.successMessage = response.data.message
						app.getAllMembers();
					}
				});
		},

		deleteMember(){
			var memForm = app.toFormData(app.clickMember);
			axios.post('api.php?crud=delete', memForm)
				.then(function(response){
					//console.log(response);
					app.clickMember = {};
					if(response.data.error){
						app.errorMessage = response.data.message;
					}
					else{
						app.successMessage = response.data.message
						app.getAllMembers();
					}
				});
		},

		selectMember(member){
			app.clickMember = member;
		},

		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.errorMessage = '';
			app.successMessage = '';
		}

	}
});
api.php
//api.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

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

$crud = 'read';

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


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

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

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

if($crud == 'create'){

	$firstname = $_POST['firstname'];
	$lastname = $_POST['lastname'];

	$sql = "insert into members (firstname, lastname) values ('$firstname', '$lastname')";
	$query = $conn->query($sql);

	if($query){
		$out['message'] = "Member Added Successfully";
	}
	else{
		$out['error'] = true;
		$out['message'] = "Could not add Member";
	}
	
}

if($crud == 'update'){

	$memid = $_POST['memid'];
	$firstname = $_POST['firstname'];
	$lastname = $_POST['lastname'];

	$sql = "update members set firstname='$firstname', lastname='$lastname' where memid='$memid'";
	$query = $conn->query($sql);

	if($query){
		$out['message'] = "Member Updated Successfully";
	}
	else{
		$out['error'] = true;
		$out['message'] = "Could not update Member";
	}
	
}

if($crud == 'delete'){

	$memid = $_POST['memid'];

	$sql = "delete from members where memid='$memid'";
	$query = $conn->query($sql);

	if($query){
		$out['message'] = "Member Deleted Successfully";
	}
	else{
		$out['error'] = true;
		$out['message'] = "Could not delete Member";
	}
	
}


$conn->close();

header("Content-type: application/json");
echo json_encode($out);
die();
?>
modal.php
//modal.php
<!-- Add Modal -->
<div class="myModal" v-if="showAddModal">
	<div class="modalContainer">
		<div class="modalHeader">
			<span class="headerTitle">Add New Member</span>
			<button class="closeBtn pull-right" @click="showAddModal = false">×</button>
		</div>
		<div class="modalBody">
			<div class="form-group">
				<label>Firstname:</label>
				<input type="text" class="form-control" v-model="newMember.firstname">
			</div>
			<div class="form-group">
				<label>Lastname:</label>
				<input type="text" class="form-control" v-model="newMember.lastname">
			</div>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" @click="showAddModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-primary" @click="showAddModal = false; saveMember();"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
			</div>
		</div>
	</div>
</div>

<!-- Edit Modal -->
<div class="myModal" v-if="showEditModal">
	<div class="modalContainer">
		<div class="editHeader">
			<span class="headerTitle">Edit Member</span>
			<button class="closeEditBtn pull-right" @click="showEditModal = false">×</button>
		</div>
		<div class="modalBody">
			<div class="form-group">
				<label>Firstname:</label>
				<input type="text" class="form-control" v-model="clickMember.firstname">
			</div>
			<div class="form-group">
				<label>Lastname:</label>
				<input type="text" class="form-control" v-model="clickMember.lastname">
			</div>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" @click="showEditModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-success" @click="showEditModal = false; updateMember();"><span class="glyphicon glyphicon-check"></span> Save</button>
			</div>
		</div>
	</div>
</div>

<!-- Delete Modal -->
<div class="myModal" v-if="showDeleteModal">
	<div class="modalContainer">
		<div class="deleteHeader">
			<span class="headerTitle">Delete Member</span>
			<button class="closeDelBtn pull-right" @click="showDeleteModal = false">×</button>
		</div>
		<div class="modalBody">
			<h5 class="text-center">Are you sure you want to Delete</h5>
			<h2 class="text-center">{{clickMember.firstname}} {{clickMember.lastname}}</h2>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" @click="showDeleteModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-danger" @click="showDeleteModal = false; deleteMember(); "><span class="glyphicon glyphicon-trash"></span> Yes</button>
			</div>
		</div>
	</div>
</div>
style.css
//style.css
.myModal{
	position:fixed;
	top:0;
	left:0;
	right:0;
	bottom:0;
	background: rgba(0, 0, 0, 0.4);
}

.modalContainer{
	width: 555px;
	background: #FFFFFF;
	margin:auto;
	margin-top:50px;
}

.modalHeader{
	padding:10px;
	background: #008CBA;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.editHeader{
	padding:10px;
	background: #4CAF50;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.deleteHeader{
	padding:10px;
	background: #f44336;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.modalBody{
	padding:40px;
}

.modalFooter{
	height:36px;
}

.footerBtn{
	margin-right:10px;
	margin-top:-9px;
}

.closeBtn{
	background: #008CBA;
	color: #FFFFFF;
	border:none;
}

.closeEditBtn{
	background: #4CAF50;
	color: #FFFFFF;
	border:none;
}

.closeDelBtn{
	background: #f44336;
	color: #FFFFFF;
	border:none;
}

Thursday, November 4, 2021

Vue.js Axios PHP How to upload multiple files

Vue.js Axios PHP How to upload multiple files

Download or Include 

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

ploadfile.html
//uploadfile.html
<!doctype html>
<html>
<head>
<title>Vue.js Axios PHP How to upload multiple files</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/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 class="container" id='myapp'>
		<br />
            <h3 align="center">Vue.js Axios PHP How to upload multiple files</h3>
        <br />
		<div class="panel panel-default">
			<div class="panel-heading"><b>Vue.js Axios PHP How to upload multiple files</b></div>
			<div class="panel-body">
				<div class="form-group">
                    <label>File Upload</label>
                    <input type="file" id="uploadfiles" ref="uploadfiles" multiple />
                </div>
                <div class="form-group">
                    <button type="button" @click='uploadFile()' class="btn btn-info" >Upload file</button>
                </div>
			<br>
			<div v-if="filenames.length" >
				<ul> 
					<li v-for= '(filename,index) in filenames' > 
						{{ filename }} 
					</li> 
				</ul>
			</div> 
			</div> 
		</div> 
	</div>
	<script>
		var app = new Vue({
			el: '#myapp',
			data: {
				file: "",
				filenames: []
			},
			methods: {
				uploadFile: function(){
					var el = this;

					let formData = new FormData();
						
					// Read selected files
					var files = this.$refs.uploadfiles.files;
					var totalfiles = this.$refs.uploadfiles.files.length;
    				for (var index = 0; index < totalfiles; index++) {
      					formData.append("files[]", files[index]);
    				}

					axios.post('upload.php', formData,
					{
						headers: {
						    'Content-Type': 'multipart/form-data'
						}
					})
					.then(function (response) {
						el.filenames = response.data;
							
						alert(el.filenames.length + " files is been uploaded.");
					})
					.catch(function (error) {
						console.log(error);
					}); 
						
				}
			}
		})
	</script>
</body>
</html>
upload.php
//upload.php
<?php
$files_arr = array();
if(isset($_FILES['files']['name'])){
	$countfiles = count($_FILES['files']['name']); // Count total files

	$upload_location = "uploads/"; // Upload directory

	// Loop all files
	for($index = 0;$index < $countfiles;$index++){

	   if(isset($_FILES['files']['name'][$index]) && $_FILES['files']['name'][$index] != ''){
	      	// File name
	      	$filename = $_FILES['files']['name'][$index];

	      	// Get extension
	      	$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

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

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

	         	// File path
	         	$newfilename = time()."_".$filename;
	         	$path = $upload_location.$newfilename;

	         	// Upload file
	         	if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
	            	$files_arr[] = $newfilename;
	         	}
	      	}
	   }
	}
}
echo json_encode($files_arr);
die;

Tuesday, October 19, 2021

Vue js PHP MySQLi Registration

Vue js PHP MySQLi Registration

In this tutorial I will show how to create a registration form and also read data and delete data from the database mysqli

vuejs CDN https://vuejs.org/v2/guide/installation.html

https://vuejs.org/

Axios is a promise-based HTTP Client for node.js and the browser. https://axios-http.com/docs/intro using Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js https://axios-http.com/docs/post_example

CREATE TABLE `user` (
  `user_id` bigint(20) NOT NULL,
  `user_name` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_email` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `user`
--

INSERT INTO `user` (`user_id`, `user_name`, `user_email`, `user_password`) VALUES
(1, 'cairocoders', 'cairocoders@gmail.com', 'pass'),
(2, 'tutorial101.blogspot.com', 'cairocoders08@gmail.com', 'pass');


ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`);

ALTER TABLE `user`
  MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;

index.php
//index.php
<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Vue js PHP MySQLi Registration</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
 </head>
 <body>
<div class="container">
	<h1 class="page-header text-center">Vue js PHP MySQLi Registration</h1>
	<div id="vueregapp">
		<div class="col-md-4">
 
			<div class="panel panel-primary">
			  	<div class="panel-heading"><span class="glyphicon glyphicon-user"></span> User Registration</div>
			  	<div class="panel-body">
			    	<label>User Name:</label>
			    	<input type="text" class="form-control" ref="username" v-model="regDetails.username" v-on:keyup="keymonitor">
			    	<div class="text-center" v-if="errorUsername">
			    		<span style="font-size:13px;">{{ errorUsername }}</span>
			    	</div>
					<label>Email:</label>
			    	<input type="text" class="form-control" ref="email" v-model="regDetails.email" v-on:keyup="keymonitor">
			    	<div class="text-center" v-if="errorEmail">
			    		<span style="font-size:13px;">{{ errorEmail }}</span>
			    	</div>
			    	<label>Password:</label>
			    	<input type="password" class="form-control" ref="password" v-model="regDetails.password" v-on:keyup="keymonitor">
			    	<div class="text-center" v-if="errorPassword">
			    		<span style="font-size:13px;">{{ errorPassword }}</span>
			    	</div>
			  	</div>
			  	<div class="panel-footer">
			  		<button class="btn btn-primary btn-block" @click="userReg();"><span class="glyphicon glyphicon-check"></span> Sign up</button>
			  	</div>
			</div>
 
			<div class="alert alert-danger text-center" v-if="errorMessage">
				<button type="button" class="close" @click="clearMessage();"><span aria-hidden="true">×</span></button>
				<span class="glyphicon glyphicon-alert"></span> {{ errorMessage }}
			</div>
 
			<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>
 
		<div class="col-md-8">
			<h3>Users Table</h3>
			<table class="table table-bordered table-striped">
				<thead>
					<th>Username</th>
					<th>Email</th>
					<th>Password</th>
					<th>Delete</th>
				</thead>
				<tbody>
					<tr v-for="user in users">
						<td>{{ user.user_name }}</td>
						<td>{{ user.user_email }}</td>
						<td>{{ user.user_password	 }}</td>
						<td><button type="button" name="delete" class="btn btn-danger btn-xs delete" @click="deleteData(user.user_id);">Delete</button></td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="vuejs.js"></script>
</body>
</html>
vuejs.js
//vuejs.js
var app = new Vue({
	el: '#vueregapp',
	data:{
		successMessage: "",
		errorMessage: "",
		errorUsername: "",
		errorEmail: "",
		errorPassword: "",
		users: [],
		regDetails: {username: '', email: '', password: ''},
	},
 
	mounted: function(){
		this.getAllUsers();
	},
 
	methods:{
		getAllUsers: function(){
			axios.get('action.php')
				.then(function(response){
					if(response.data.error){
						app.errorMessage = response.data.message;
					}
					else{
						app.users = response.data.users;
					}
				});
		},
 
		userReg: function(){
			var regForm = app.toFormData(app.regDetails);
			axios.post('action.php?action=register', regForm)
				.then(function(response){
					console.log(response);
					if(response.data.username){
						app.errorUsername = response.data.message;
						app.focusUsername();
						app.clearMessage();
					}
					else if(response.data.email){
						app.errorEmail = response.data.message;
						app.focusEmail();
						app.clearMessage();
					}
					else if(response.data.password){
						app.errorPassword = response.data.message;
						app.errorEmail='';
						app.focusPassword();
						app.clearMessage();
					}
					else if(response.data.error){
						app.errorMessage = response.data.message;
						app.errorEmail='';
						app.errorPassword='';
					}
					else{
						app.successMessage = response.data.message;
					 	app.regDetails = {email: '', password:''};
					 	app.errorEmail='';
						app.errorPassword='';
					 	app.getAllUsers();
					}
				});
		},
 
		focusUsername: function(){
			this.$refs.username.focus();
		},		
		
		focusEmail: function(){
			this.$refs.email.focus();
		},
 
		focusPassword: function(){
			this.$refs.password.focus();
		},
 
		keymonitor: function(event) {
       		if(event.key == "Enter"){
         		app.userReg();
        	}
       	},
 
		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.errorMessage = '';
			app.successMessage = '';
		},
		
		deleteData: function(user_id){ //alert(user_id)
			if(confirm("Are you sure you want to remove this data?")){ 
				axios.post('action.php?action=delete&id='+ user_id +'', {
				 action:'delete',
				}).then(function(response){
					alert(response.data.message);
					app.getAllUsers();
				});
			}
		}
 
	}
});
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, 'username'=> false, 'email'=> false, 'password' => false);
 
$action = 'alldata';
 
if(isset($_GET['action'])){
	$action = $_GET['action'];
}
 
 
if($action == 'alldata'){
	$sql = "select * from user";
	$query = $conn->query($sql);
	$users = array();
 
	while($row = $query->fetch_array()){
		array_push($users, $row);
	}
 
	$out['users'] = $users;
}
 
if($action == 'register'){
 
	function check_input($data) {
	  $data = trim($data);
	  $data = stripslashes($data);
	  $data = htmlspecialchars($data);
	  return $data;
	}
 
	$username = check_input($_POST['username']);
	$email = check_input($_POST['email']);
	$password = check_input($_POST['password']);
 
	if($username==''){
		$out['username'] = true;
		$out['message'] = "User Name is required";
	}	
	
	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($password==''){
		$out['password'] = true;
		$out['message'] = "Password is required";
	}
 
	else{
		$sql="select * from user where user_email='$email'";
		$query=$conn->query($sql);
 
		if($query->num_rows > 0){
			$out['email'] = true;
			$out['message'] = "Email already exist";
		}
 
		else{
			$sql = "insert into user (user_name, user_email, user_password) values ('$username', '$email', '$password')";
			$query = $conn->query($sql);
 
			if($query){
				$out['message'] = "User Added Successfully";
			}
			else{
				$out['error'] = true;
				$out['message'] = "Could not add User";
			}
		}
	}
}

if($action == 'delete'){

	$del = $_GET['id'];                              
	$sqldel = "DELETE FROM user WHERE user_id = '".$del."'";
    $conn->query($sqldel);
	  
	$out['message'] = "Deleted $del";
	
}

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

Sunday, October 17, 2021

Vue.js PHP fetchAll Data from Mysql Database

Vue.js PHP fetchAll Data from Mysql Database

https://vuejs.org/

Axios is a promise-based HTTP Client for node.js and the browser. https://axios-http.com/docs/intro using Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js https://axios-http.com/docs/post_example


CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL,
  `photo` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


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

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


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

fetchdata.php
//fetchdata.php
<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Vue.js PHP fetchAll Data from Mysql Database</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
  <div class="container" id="fetchAlldiv">
   <br />
   <h3 align="center">Vue.js PHP fetchAll Data from Mysql Database</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
       <h3 class="panel-title"> Employee Records</h3>
     </div>
    </div>
    <div class="panel-body">
		<div class="table-responsive">
		  <table class="table table-bordered table-striped">
		   <tr>
			<th>Name</th>
			<th>Position</th>
			<th>Office</th>
			<th>Edit</th>
			<th>Delete</th>
		   </tr>
		   <tr v-for="row in allData">
			<td>{{ row.name }}</td>
			<td>{{ row.position }}</td>
			<td>{{ row.office }}</td>
			<td><button type="button" name="edit" class="btn btn-primary btn-xs edit">Edit</button></td>
			<td><button type="button" name="delete" class="btn btn-danger btn-xs delete">Delete</button></td>
		   </tr>
		  </table>
		</div>
    </div>
   </div>
  </div>
<script src="js_fetchdata.js"></script>
</body>
</html>
js_fetchdata.js
//js_fetchdata.js
var application = new Vue({
	el:'#fetchAlldiv',
		data:{
		  allData:'',
	},
	methods:{
		fetchAllData:function(){ //show records
		   axios.post('fetchall.php', {
			action:'fetchall'
		   }).then(function(response){
			application.allData = response.data;
		   });
		}
	}, 
	created:function(){
	  this.fetchAllData();
	}
});
fetchall.php
//fetchall.php
<?php 
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");
$received_data = json_decode(file_get_contents("php://input"));

$data = array();
if($received_data->action == 'fetchall') //axios.post('fetchall.php', { action:'fetchall'
{
	$query = "
	 SELECT * FROM employee 
	 ORDER BY id DESC
	 ";
	$statement = $connect->prepare($query);
	$statement->execute();
	while($row = $statement->fetch(PDO::FETCH_ASSOC))
	{
	  $data[] = $row;
	}
	echo json_encode($data);
	
}

?>

Related Post