Showing posts with label vue js tutorial. Show all posts
Showing posts with label vue js tutorial. Show all posts

Friday, 22 May 2020

Check Username or Email Availability using Vue.js with PHP



In this Vue.js tutorial, we will make PHP script for implement username or email live check for registration feature using Vue.js with Axios package for send Ajax request. This functionality is very common and it is required feature for most of the websites which is available online. If in your website, you have give login rights to user by entering their username or email and password, and get access into websites. Then at that time their username or email address must be unique. For this things when user has come into your websites for new account registration, then at that time we have to check username or email is available for registration or not for prevent duplicate registration with same username or email address.

For this problem, In this tutorial, we will use Vue.js with PHP script for check username of email already exists in our Mysql database or not. If Username or email is already exists then at that time we have stop user registration process by displaying message like particular email or username is already registered in our system try with different username or email address, and it will notify to the user regarding email address or username is already used by some another person before submitting of registration form data. Now in your mind one question will arise, how to check email ID or username exist or not in database, for this we will use Ajax with Vue.js and PHP script. When user has type something in username or email textbox then Vue.js will send Ajax request to PHP script with query like for search particular username or email address already exists in Mysql database.

This we can done when User has create account in our website, so while user enters their username or email id then Vue.js will triggered Ajax call and it will send request to PHP script at server side to check the availability status of email address or username. At PHP script, it will matches user data which they have enter with data available in Mysql database and it will send back response to Ajax request with availability of Username or email address which will be display on web page by using Vue.js without refresh of web page. So checking of availability of Email Address or Username of the user at the time registration is the best way to prevent duplicate registration in our web application. So from this tutorial, you can learn how to check email id or username availability of user from database, this things here we will use Ajax with Vue.js and PHP script. Below you can find the complete source code of how to check availability of the username or email address using ajax and Vue.js in PHP.


Check Username or Email Availability using Vue.js with PHP




Source Code


Mysql Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_login`
--

CREATE TABLE `tbl_login` (
  `id` int(11) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `gender` varchar(30) NOT NULL,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
  `address` text NOT NULL,
  `mobile_no` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_login`
--

INSERT INTO `tbl_login` (`id`, `first_name`, `last_name`, `gender`, `email`, `password`, `address`, `mobile_no`) VALUES
(1, 'John', 'Smith', 'male', 'johnsmith@gmail.com', '$2y$10$vgo3NI5w5cLB74E4B2sdVuKwdSpJL/EAeKSUdevkc/j3zl0sJAf5i', 'test address', '9632587410');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_login`
--
ALTER TABLE `tbl_login`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_login`
--
ALTER TABLE `tbl_login`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;





index.php



<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Live Username Or Email Availability using Vue.js in 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/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
 </head>
 <body>
  <div class="container" id="registerApp">
   <br />
   <h3 align="center">Live Username Or Email Availability using Vue.js in PHP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Register</h3>
    </div>
    <div class="panel-body">
     <div class="form-group">
      <label>Enter Your Email</label>
      <input type="text" v-model="email" class="form-control input-lg" :class="class_name" @keyup="check()" />
      <span :class="[dynamic_class ? 'success' : 'danger']">{{ message }}</span>
     </div>
     <div class="form-group">
      <label>Enter Your Password</label>
      <input type="password" v-model="password" class="form-control input-lg" />
     </div>
     <div class="form-group" align="center">
      <button type="button" :disabled="is_disable" class="btn btn-info btn-lg">Register</button>
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<style>
.success
{
 font-weight: bold;
 color:#009933;
 background-color: #ccffcc;
 border:1px solid #009933;
}

.danger
{
 font-weight: bold;
 color:#ff0000;
 background-color: #ffe6e6;
 border:1px solid #ff0000;
}
</style>

<script>

var application = new Vue({
 el:'#registerApp',
 data:{
  email:'',
  dynamic_class:true,
  message:'',
  password:'',
  is_disable:false,
  class_name:''
 },
 methods:{
  check:function(){
   var email = application.email.trim();
   if(email.length > 2)
   {
    axios.post('action.php', {
     email:email
    }).then(function(response){
     if(response.data.is_available == 'yes')
     {
      application.dynamic_class = true;
      application.message = 'This Email is Available for Registration';
      application.is_disable = false;
      application.class_name = 'success';
     }
     else
     {
      application.dynamic_class = false;
      application.message = 'This Email is already registred';
      application.is_disable = true;
      application.class_name = 'danger';
     }
    });
   }
   else
   {
    application.message = '';
    application.class_name = '';
    application.dynamic_class = true;
    application.is_disable = false;
   } 
  }
 }
});

</script>


action.php



<?php

//action.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

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

$data = array();

if($received_data->email != '')
{
 $is_available = 'yes';

 $query = "
 SELECT * FROM tbl_login 
 WHERE email = '".$received_data->email."'
 ";

 $statement = $connect->prepare($query);

 $statement->execute();

 $total_row = $statement->rowCount();

 if($total_row > 0)
 { 
  $is_available = 'no';
 }

 $data = array(
  'is_available'  => $is_available
 );
}

echo json_encode($data);

?>


If you like this tutorial and you have found that this tutorial helpful then please don't forget to share this tutorial.

Friday, 24 April 2020

Build CRUD App using Vue.js PHP MySql



This is first tutorial on Vue.js with PHP script and in this tutorial we will make CRUD Application in PHP by using Vue.js and Axios package. For learn any new web technology for web development, then first we have to learn How can we do insert update delete operation with Mysql database. For this also for learn How to use Vue.js for website development, first we want to learn How to create CRUD application using Vue.js. By using CRUD application we will learn Create, Read, Update and Delete mysql data operation by using Vue.js with PHP script. From this post you can easily learn How can we perform insert update delete mysql data operation by using Vue.js with PHP script.

We all know Add, edit and delete feature is mostly used in developing of every dynamic website and by using PHP script we can make dynamic website. But only by using PHP script we can make dynamic website, but on every button click page has been refresh. By using Ajax with PHP script we can improve user experience by performing all operation without page refresh. But here we have use Vue.js and Axios package with PHP script then we can perform all form related operation without refresh of web page just like desktop application. So, here we will make single page CRUD application using Vue.js with PHP script.

In this post, we will learn you, how can we select, insert, update and delete mysql data from database using Vue.js with PHP and Axios package. Here we will use Axios package in place of Ajax for perform all operation without refresh of web page. So, if you wanted to learn How to make Single Page Crud application using Vue.js with PHP script and Mysql database. Below you can find the feature of this PHP CRUD app using Vue.js library.

  1. Fetch Data Mysql Database using Vue.js with PHP
  2. Make Modal in Vue.js
  3. Insert or Add Data using Vue.js with PHP
  4. Update or Edit Data using Vue.js with PHP
  5. Delete or Remove Data using Vue.js with PHP

Build CRUD App using Vue.js PHP MySql




Database


First we have to make table in Mysql database, for this we have to run following SQL script in your Mysql localhost but before run following SQL script, you have to create database and then after run below SQL script. It will make tbl_sample table in your local mysql database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_sample`
--

CREATE TABLE `tbl_sample` (
  `id` int(11) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_sample`
--

INSERT INTO `tbl_sample` (`id`, `first_name`, `last_name`) VALUES
(1, 'John', 'Smith'),
(2, 'Peter', 'Parker'),
(4, 'Donna', 'Huber');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_sample`
--
ALTER TABLE `tbl_sample`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_sample`
--
ALTER TABLE `tbl_sample`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;





index.php


In this file we have write all client side code like HTML and Vue.js code. For use Vue.js with Axios package, first we have to include following library link at the header of this page.


<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


For display mysql data on web page, first we have make HTML table and then after by using v-for directive for fetch data from Vue.js placeholder data and print in HTML table.

After this for make Modal in Vue.js. For create modal in Vue.js here we will use Bootstrap modal. For make modal in Vue.js library here we have use transition tag, Under this tag, we have define bootstrap modal code and then after we can make modal in Vue.js

index.php

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>PHP Insert Update Delete with Vue.js</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>
  <style>
   .modal-mask {
     position: fixed;
     z-index: 9998;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
     background-color: rgba(0, 0, 0, .5);
     display: table;
     transition: opacity .3s ease;
   }

   .modal-wrapper {
     display: table-cell;
     vertical-align: middle;
   }
  </style>
 </head>
 <body>
  <div class="container" id="crudApp">
   <br />
   <h3 align="center">Delete or Remove Data From Mysql using Vue.js with PHP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">
       <h3 class="panel-title">Sample Data</h3>
      </div>
      <div class="col-md-6" align="right">
       <input type="button" class="btn btn-success btn-xs" @click="openModel" value="Add" />
      </div>
     </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>Edit</th>
        <th>Delete</th>
       </tr>
       <tr v-for="row in allData">
        <td>{{ row.first_name }}</td>
        <td>{{ row.last_name }}</td>
        <td><button type="button" name="edit" class="btn btn-primary btn-xs edit" @click="fetchData(row.id)">Edit</button></td>
        <td><button type="button" name="delete" class="btn btn-danger btn-xs delete" @click="deleteData(row.id)">Delete</button></td>
       </tr>
      </table>
     </div>
    </div>
   </div>
   <div v-if="myModel">
    <transition name="model">
     <div class="modal-mask">
      <div class="modal-wrapper">
       <div class="modal-dialog">
        <div class="modal-content">
         <div class="modal-header">
          <button type="button" class="close" @click="myModel=false"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title">{{ dynamicTitle }}</h4>
         </div>
         <div class="modal-body">
          <div class="form-group">
           <label>Enter First Name</label>
           <input type="text" class="form-control" v-model="first_name" />
          </div>
          <div class="form-group">
           <label>Enter Last Name</label>
           <input type="text" class="form-control" v-model="last_name" />
          </div>
          <br />
          <div align="center">
           <input type="hidden" v-model="hiddenId" />
           <input type="button" class="btn btn-success btn-xs" v-model="actionButton" @click="submitData" />
          </div>
         </div>
        </div>
       </div>
      </div>
     </div>
    </transition>
   </div>
  </div>
 </body>
</html>

<script>

var application = new Vue({
 el:'#crudApp',
 data:{
  allData:'',
  myModel:false,
  actionButton:'Insert',
  dynamicTitle:'Add Data',
 },
 methods:{
  fetchAllData:function(){
   axios.post('action.php', {
    action:'fetchall'
   }).then(function(response){
    application.allData = response.data;
   });
  },
  openModel:function(){
   application.first_name = '';
   application.last_name = '';
   application.actionButton = "Insert";
   application.dynamicTitle = "Add Data";
   application.myModel = true;
  },
  submitData:function(){
   if(application.first_name != '' && application.last_name != '')
   {
    if(application.actionButton == 'Insert')
    {
     axios.post('action.php', {
      action:'insert',
      firstName:application.first_name, 
      lastName:application.last_name
     }).then(function(response){
      application.myModel = false;
      application.fetchAllData();
      application.first_name = '';
      application.last_name = '';
      alert(response.data.message);
     });
    }
    if(application.actionButton == 'Update')
    {
     axios.post('action.php', {
      action:'update',
      firstName : application.first_name,
      lastName : application.last_name,
      hiddenId : application.hiddenId
     }).then(function(response){
      application.myModel = false;
      application.fetchAllData();
      application.first_name = '';
      application.last_name = '';
      application.hiddenId = '';
      alert(response.data.message);
     });
    }
   }
   else
   {
    alert("Fill All Field");
   }
  },
  fetchData:function(id){
   axios.post('action.php', {
    action:'fetchSingle',
    id:id
   }).then(function(response){
    application.first_name = response.data.first_name;
    application.last_name = response.data.last_name;
    application.hiddenId = response.data.id;
    application.myModel = true;
    application.actionButton = 'Update';
    application.dynamicTitle = 'Edit Data';
   });
  },
  deleteData:function(id){
   if(confirm("Are you sure you want to remove this data?"))
   {
    axios.post('action.php', {
     action:'delete',
     id:id
    }).then(function(response){
     application.fetchAllData();
     alert(response.data.message);
    });
   }
  }
 },
 created:function(){
  this.fetchAllData();
 }
});

</script>


action.php


All php script will be write under this file for make CRUD application. In this file, first we want to make database connection. After this we have to receive Axios request data in json format. For received JSON data at PHP script, we have use file_get_contents() function and then after by using json_decode() function, json string data will be converted into PHP array object. After this, we have write PHP script for Select, Insert, Update and Delete mysql data operation.

action.php

<?php

//action.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$received_data = json_decode(file_get_contents("php://input"));
$data = array();
if($received_data->action == 'fetchall')
{
 $query = "
 SELECT * FROM tbl_sample 
 ORDER BY id DESC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 while($row = $statement->fetch(PDO::FETCH_ASSOC))
 {
  $data[] = $row;
 }
 echo json_encode($data);
}
if($received_data->action == 'insert')
{
 $data = array(
  ':first_name' => $received_data->firstName,
  ':last_name' => $received_data->lastName
 );

 $query = "
 INSERT INTO tbl_sample 
 (first_name, last_name) 
 VALUES (:first_name, :last_name)
 ";

 $statement = $connect->prepare($query);

 $statement->execute($data);

 $output = array(
  'message' => 'Data Inserted'
 );

 echo json_encode($output);
}
if($received_data->action == 'fetchSingle')
{
 $query = "
 SELECT * FROM tbl_sample 
 WHERE id = '".$received_data->id."'
 ";

 $statement = $connect->prepare($query);

 $statement->execute();

 $result = $statement->fetchAll();

 foreach($result as $row)
 {
  $data['id'] = $row['id'];
  $data['first_name'] = $row['first_name'];
  $data['last_name'] = $row['last_name'];
 }

 echo json_encode($data);
}
if($received_data->action == 'update')
{
 $data = array(
  ':first_name' => $received_data->firstName,
  ':last_name' => $received_data->lastName,
  ':id'   => $received_data->hiddenId
 );

 $query = "
 UPDATE tbl_sample 
 SET first_name = :first_name, 
 last_name = :last_name 
 WHERE id = :id
 ";

 $statement = $connect->prepare($query);

 $statement->execute($data);

 $output = array(
  'message' => 'Data Updated'
 );

 echo json_encode($output);
}

if($received_data->action == 'delete')
{
 $query = "
 DELETE FROM tbl_sample 
 WHERE id = '".$received_data->id."'
 ";

 $statement = $connect->prepare($query);

 $statement->execute();

 $output = array(
  'message' => 'Data Deleted'
 );

 echo json_encode($output);
}

?>


Remaining source code will be added very soon.