Fetch Data from MySQL Database using Vuejs in PHP

January 4, 2021
PHP
Fetch Data from MySQL Database using Vue.js in PHP

Tutorial: Fetch Data from MySQL Database using Vuejs in PHP

Getting Started

I’ve used CDN for bootstrap, vue.js, and axios.js in this tutorial so, you need an internet connection for them to work.

index.php

First, we’re going to create our index which contains our Form that we are going to validate.

<!DOCTYPE html>
<html>
<head>
    <title>Input Validation using Vue.js with PHP</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <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>
    <style type="text/css">
        .div-space{
            height:20px;
        }
        .demo-label{
            margin-top:7px;
        }
        .top-margin{
            margin-top:10px;
        }
        .error{
            font-size:13px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="page-header text-center">Input Validation using Vue.js with PHP</h1>
        <div id="validate">
            <div class="row">
                <div class="col-md-10 col-md-offset-1">
                    <div class="alert alert-success text-center" v-if="successMessage">
                        <button type="button" class="close" @click="clearMessage();"><span aria-hidden="true">&times;</span></button>
                        <span class="glyphicon glyphicon-check"></span> {{ successMessage }}
                    </div>
                    <div class="panel panel-primary">
                        <div class="panel-heading">
                            Input Form
                        </div>
                        <div class="panel-body">
                            <div class="top-margin"></div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="col-md-3">
                                            <label class="demo-label">Username:</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="text" ref="username" class="form-control" v-model="forValidation.username">
                                            <div v-if="errorUsername" class="error">{{ errorUsername }}</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="col-md-3">
                                            <label class="demo-label">Password:</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="password" ref="password" class="form-control" v-model="forValidation.password">
                                            <div v-if="errorPassword" class="error">{{ errorPassword }}</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="div-space"></div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="col-md-3">
                                            <label class="demo-label">Firstname:</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="text" ref="firstname" class="form-control" v-model="forValidation.firstname">
                                            <div v-if="errorFirstname" class="error">{{ errorFirstname }}</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="col-md-3">
                                            <label class="demo-label">Lastname:</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="text" ref="lastname" class="form-control" v-model="forValidation.lastname">
                                            <div v-if="errorLastname" class="error">{{ errorLastname }}</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="div-space"></div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="col-md-3">
                                            <label class="demo-label">Email:</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="text" ref="email" class="form-control" v-model="forValidation.email">
                                            <div v-if="errorEmail" class="error">{{ errorEmail }}</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="col-md-3">
                                            <label class="demo-label">Website:</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="text" ref="website" class="form-control" v-model="forValidation.website">
                                            <div v-if="errorWebsite" class="error">{{ errorWebsite }}</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="div-space"></div>
                        </div>
                        <div class="panel-footer">
                            <button class="btn btn-primary" @click="validateInput();"><span class="glyphicon glyphicon-check"></span> Validate</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
<script src="app.js"></script>
</body>
</html>

app.js

This contains our Vue.js code.

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

Lastly, this is our PHP code that will validate our input.

<?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();
 
 
?>
Fetch Data from MySQL Database using Vue.js in PHP

Fetch Data from MySQL Database using Vue.js in PHP

That ends this tutorial. Happy Coding!

Download Here
Facebook Comments

Leave a Reply

Your email address will not be published.