article

Saturday, November 13, 2021

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//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>
</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="applogin.js"></script>
</body>
</html>
applogin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//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
1
2
3
4
5
6
7
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
success.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//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>
</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
1
2
3
4
5
6
//logout.php
<?php
    session_start();
    session_destroy();
    header('location:index.php');
?>

Related Post