Friday, 17 May 2019

Online Student Attendance System Project in PHP



Do you know Online Attendance Management System is an advance tool, which help us to manage and maintain the records of student attendance. This type of tool mainly a one type of software that keep observe attendance details.

Here this is online system, that means this system has very useful technique, because this system we can access from anywhere from any device, because this system has been develop by responsive web technology.

This is very simple and user friendly attendance management system for teacher, who want to digitize their student attendance record online. Digitize means convert paper work process into digital form, and store all data online, So he can view all details in single click.

For make this student attendance system, we have use all opensource technology like PHP, Mysql, jQery, Ajax, Bootstrap 4, jQuery Datatable plugin, Bootstrap Datepicker plugin. If you are looiking for your College project, then you can use this system in your education project also.

So, are you ready for learn how to make simple Student Attendance system in PHP and Mysql. So you have come on right place with right time, because here we have make tutorial on attendance management system by using latest web technology.

Features of Attendance Management System


The main feature of this Student Attendance system is that store student daily attendance record, and make PDF report from attendance data. This is very simple system, there are main two user, one is admin and other one is teacher. Admin has all rights for view or access system data, while teacher has rights to view only his or her grade student data. In this system Admin and teacher password has been store in encrypted form.

User of this System


  • Admin
  • Teacher

Admin Activity


  • Admin can Add Update Delete Grade Master Data
  • Admin has rights to add new teacher account, edit teacher details, and remove teacher account
  • Admin can assign grade to teacher, so teacher can view his or her student and take attendace of that student only.
  • Admin can Add new student, edit existing student and delete student data. Student grade also assign by admin only.
  • Admin can view all student attendance records of any grade.
  • Admin can make pdf report of any student attendance record
  • Admin can view all student overall attendance details in percentage form.

Teacher Activity


  • Teacher can update his or her profile details like change password, change profile picture etc
  • Teacher can view his or her grade student list.
  • Teacher can take attendance of his or her grade student.
  • Teacher can view his or her grade student attendance details
  • Teacher can generate PDF report of Attendance records.
  • Teacher can view overall attendance percentage of all student of his or her grade.

We have following Web Technology has been used for this attendance management system.



Database Structure




Directory Stucture

Below you can find directory structure of this attendance management system project in PHP.




admin/database_connection.php



<?php

//database_connection.php

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

$base_url = "http://localhost/tutorial/student-attendance-system-in-php-using-ajax/";

?>


admin/login.php



<?php

//login.php

include('database_connection.php');

session_start();

if(isset($_SESSION["admin_id"]))
{
  header('location:index.php');
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Student Attendance System in PHP using Ajax</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="jumbotron text-center" style="margin-bottom:0">
  <h1>Student Attendance System</h1>
</div>


<div class="container">
  <div class="row">
    <div class="col-md-4">

    </div>
    <div class="col-md-4" style="margin-top:20px;">
      <div class="card">
        <div class="card-header">Admin Login</div>
        <div class="card-body">
          <form method="post" id="admin_login_form">
            <div class="form-group">
              <label>Enter Username</label>
              <input type="text" name="admin_user_name" id="admin_user_name" class="form-control" />
              <span id="error_admin_user_name" class="text-danger"></span>
            </div>
            <div class="form-group">
              <label>Enter Password</label>
              <input type="password" name="admin_password" id="admin_password" class="form-control" />
              <span id="error_admin_password" class="text-danger"></span>
            </div>
            <div class="form-group">
              <input type="submit" name="admin_login" id="admin_login" class="btn btn-info" value="Login" />
            </div>
          </form>
        </div>
      </div>
    </div>
    <div class="col-md-4">

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

</body>
</html>

<script>
$(document).ready(function(){
  $('#admin_login_form').on('submit', function(event){
    event.preventDefault();
    $.ajax({
      url:"check_admin_login.php",
      method:"POST",
      data:$(this).serialize(),
      dataType:"json",
      beforeSend:function(){
        $('#admin_login').val('Validate...');
        $('#admin_login').attr('disabled', 'disabled');
      },
      success:function(data)
      {
        if(data.success)
        {
          location.href = "<?php echo $base_url; ?>admin";
        }
        if(data.error)
        {
          $('#admin_login').val('Login');
          $('#admin_login').attr('disabled', false);
          if(data.error_admin_user_name != '')
          {
            $('#error_admin_user_name').text(data.error_admin_user_name);
          }
          else
          {
            $('#error_admin_user_name').text('');
          }
          if(data.error_admin_password != '')
          {
            $('#error_admin_password').text(data.error_admin_password);
          }
          else
          {
            $('#error_admin_password').text('');
          }
        }
      }
    });
  });
});
</script>


admin/header.php



<?php

//header.php

include('database_connection.php');

session_start();

if(!isset($_SESSION["admin_id"]))
{
  header('location:login.php');
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Student Attendance System in PHP using Ajax</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>!-->
  <link rel="stylesheet" href="../css/bootstrap.min.css">
  <link rel="stylesheet" href="../css/dataTables.bootstrap4.min.css">
  <script src="../js/jquery.min.js"></script>
  <script src="../js/popper.min.js"></script>
  <script src="../js/bootstrap.min.js"></script>
  <script src="../js/jquery.dataTables.min.js"></script>
  <script src="../js/dataTables.bootstrap4.min.js"></script>
</head>
<body>

<div class="jumbotron-small text-center" style="margin-bottom:0">
  <h1>Student Attendance System</h1>
</div>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
  <a class="navbar-brand" href="index.php">Home</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="grade.php">Grade</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="teacher.php">Teacher</a>
      </li>
      
      <li class="nav-item">
        <a class="nav-link" href="student.php">Student</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="attendance.php">Attendance</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="logout.php">Logout</a>
      </li>  
    </ul>
  </div>  
</nav>


admin/index.php



<?php

//index.php

include('header.php');

?>

<div class="container" style="margin-top:30px">
  
</div>

</body>
</html>

<script>
$(document).ready(function(){
 

});
</script>


admin/logout.php



<?php

//logout.php

session_start();

session_destroy();

header('location:login.php');


?>


Source Code of Student Attendance Management System using PHP will be available very soon.




15 Tips for Web Development Success



Whether you’re a beginner at web design or a wizened pro, here are some pointers that can help you make your web design work better:

1.Prioritize the speed.


No one likes to wait. This is why it is important for you to ensure that your website is fast.

The trick to this is to optimize the image files in the page. Transform raw image files into a more compact format so that they won’t strain your site’s loading speed.

2.Ensure smooth navigation.


Every website has one true aim, and that is to enhance the conversion rate of web visitors.

Place an intuitive and straightforward web design in play, and your clients won’t have to worry about getting lost on your website.

3.Optimize the site for mobile use.


Not everyone has a computer. But you can bet that almost everybody has a phone. And you can use this to your advantage! By configuring your website for smartphone use, your market will be able to expand to mobile users all over the world.

4.Choose the complementary color pattern.


Pick a color scheme that looks harmonious. If you’re not an expert in picking color combinations, consulting a color wheel or referencing existing palettes online might help.

5.Utilize the right font.


It’s okay to go for style, but your readability should be your top priority when selecting a font. After all, fancy looking typefaces are deemed useless when your clients can’t understand them.

6.Place the headline where it needs to be.


Up top, dead center is usually the go-to. However, you don't always have to follow the standard. It's okay to be creative. The important thing is that your headline is able to capture your audience and make them feel welcome when they first enter your page.

7.Situate the logo and CTA buttons.


This will enhance brand recognition and help your clients take the action that they want, easily. Be sure not to clutter all the buttons in one place either as it might cause confusion!

8.Add the social sharing buttons.


Not all clients make a purchase, but you can encourage them to share your content. Simply place social sharing buttons at the line of sight, and your brand will have an easier time gaining popularity.

9. Reinforce the search bar.


When you’re looking for something in a website, do you take the time to scour every single page? Not everyone does. Having a search bar can deliver your prospects the content that they want with minimum effort. The more convenient your page is to use, the more your site will be able to gain an online audience.

10.Include the necessary pages.


It’s fairly tempting to just set up one page and call it a day, but you shouldn’t. Not only will it make your business website look sketchy, but generally clients want a bit of information before they subscribe to a service or brand. (You probably would too, as a consumer!)

To start off, here are the basic pages your website should have:

Homepage

This segment is for telling the audience about your brand, along with the products and services that come with it. The key factor to make the homepage work is to focus on building user interaction, rather than the overall design.

About us

This segment is for giving web users a summary of your brand’s reliability and integrity.

Contact us

This segment is for giving clients the option to contact you as soon as possible should they have any concerns regarding your brand.

Products and services

This segment is for showcasing what your brand has to offer.

Terms and Conditions

This segment is for detailing the fair usage policy of the website.

Privacy Policy

This segment is for reassuring clients that the data they input in your website will be protected.

11.Check the cross-compatibility through different browsers.


Not everyone uses the same web browser. Doubt it? Go ahead and ask a group of friends and relatives. You’ll be surprised by the diversity.

<a name="_GoBack"></a>

That’s all fun and good, but the thing is, not all web browsers display pages the same way. Your site might look good in one web browser, but it may absolutely be off center in another. To sort it out, you will need to test your web design across multiple web browsers to make sure everything is in order.

12. Avoid free themes, extensions, and plugins.


Saving money is important, but are they always the best option? At first glance, maybe. But, you should be careful as certain free themes, extensions, and plugins may actually come with malware that can affect the performance of your site and make it unsafe for your web users. Go for premium options instead. They may be a bit pricey, but you can rest assured that they are safe.

13. Include the multilingual option.


The world wide web is a vast place. And because of that, everyone from all over the planet is able to access your site. Still, you have to consider that English is not everyone’s first language. As a solution, you should install a plugin that will readily translate your site’s content. Through it, your brand will have a greater pull on the international market.

14. Append the needed security measures.


With the rise of scammers online, internet users tend to be more careful in selecting the sites they visit. And if you don’t want your site to be avoided, you might want to consider installing an HTTPS batch file. This is a type of security protocol which encrypts data transfer, preventing any unauthorized access. With it, clients are less likely to second guess your website.

15. Keep the design simple.


The easier it can be understood, the better. Keep your mindset in the shoes of a consumer. If you think that your site is able to offer what is desired in an effortless and convenient manner, then it’s good to go!

Was this post helpful for you?

Share it with friends!

About Author


I am Louise Savoie Digital Marketer at Proweaver, a web development company specializing in Custom Web Design which helps sole proprietors and small companies increase their sales and grow their business. I am responsible in Content Marketing and Social Media Marketing. You can find us on Twitter: @proweaver

Wednesday, 8 May 2019

MySQL vs. MongoDB : Which One To Opt For?

Today, in this technology era, new enterprises and companies thinking about to store and manage data in a better way to get vast customer insights. And we can also stick with the new user expectations, or beat competitors market with new business models and applications.




Considering the best DBMS is always a hurdle task in this technology world because too many choices to select from. DBMS classified into two types, i.e. relational and non-relational. In recent years relational Database systems like PostgreSQL, MySQL usage vastly increased.

On the other side, non relational Database management systems like MongoDB. These are able to storing and managing the large volumes of data.

Let us discuss that, which DBMS is best by considering the relational and non- relational DBMS viz.MongoDB and MySQL.

So, let us deep dive into the comparison of MongoDB and MySQL

What is MySQL?


MySQL is an advanced open source Relational DBMS. It is developed, supported, and distributed by Oracle. MySQL stores and manages data using tables and SQL(structured query language) for accessing the database. SQL language is used in a server called SQL Server Databases.

It uses simple commands such as "INSERT" "DELETE" "UPDATE" "SELECT" to access and manage the data. MySQL allows you to pre-define database schema based on your setup and requirements to oversee the connections between fields and tables.

What is MongoDB?


MongoDB is popularly known as a non relational database system. In MongoDB, the data stored in the form of document format in a binary representation model called BSON. Related information is stored collectively for quick query access by the MongoDB.

In MongoDB, a document is called a big JSON object. Which contains no particular schema or format. For any kind of query access, related data is stored by using MongoDB query language. This process is different for various kind of fields.

If a new type of field requires to be combined with a document, then the field can be generated without altering all other documents in the collection process, without taking the system offline and updating a central system catalog. Essentially, schema validation is used to support data governance handles over each collection.

Data Storage and Structure


As we already know that the MySQL follows the relational model database system. In which data is stored in the form of tables. Along with you have to predefined the schema depends on the requirements between fields and tables.

On the other side, in MongoDB data is stored in the form of documents in a collection format. This major difference is a great support to the developers. Because of the code define the schema and there is no need to go with the schema migrations in the future.

Terminology Comparison and Concepts


Many notions in MongoDB have close analogues in MySQL. The below-mentioned table describes the common connections between MongoDB and MySQL.

MongoDB MySQL
Collection Table
Field Column
Aggregation Pipeline Group_BY
Secondary Index Secondary Index
ACID Transactions ACID Transactions




Query Language and Syntax Comparison


MongoDB and MySQL query languages are strong. An unstructured query language used by MongoDB. And the documents stored in the form of big JSON file formats. In the time of the execution process of MongoDB, different types of the operator are used and these are similar to document file JSON. MongoDB supports boolean queries.

On the other side, MySQL works with the structured query language, while accessing the database. Perhaps it is quite simple. This language very strong, and consisting of two parts in it.
DDL (Data Definition Language)
DML(Data Manipulation Language)

Selecting records from the required table for the example:

MySQL:


SELECT * FROM table_name

MongoDB:


db.table_name.find()




Inserting records into the required table and is mentioned below:

MySQL:


INSERT INTO table_name (cust_id, branch, status) VALUES ('app1', 'sub', 'C')

MongoDB:


$db.table_name.insert({ cust_id: 'app1', branch: 'sub', status: 'C'})






Some of the concepts are mentioned below.

SQL Concepts MongoDB Concepts
SELECT $project
LIMIT $limit
join $lookup
ORDER BY $sort
COUNT $sum

Performance and Speed


In MySQL, data is dispersed across multiple tables, so at the same time, various tables need to manage to write and read data. Whereas in MongoDB all the documents stored in a single entity called JSON file, this is the reason accessing the data is very fast. This creates to write and read the entire data in a single owned document. Although MySQL supports JSON, but it might not be given the same advantages as MongoDB gives.

MySQL is slow compared to MongoDB because it uses massive volumes of data. When the data volume is greater, it cannot deal with the unstructured language.

Developer Productivity


Producing applications in MySQL is a slow process because it uses the rigid table structured model. In the same case working with JSON document in MongoDB has vast development cycles by up to 4 to 5 times. MongoDB documents map directly to Oops, so it is easier for developers to visualize and understand how data in application will be merged into the database.

Security Model


MongoDB can build its control with a variable set of perquisites. And it includes key security features like auditing, authorization, and authentication, etc. It will also support SSL(secure sockets layer) and TLS(transport layer security) to encrypt the server side end. This will make sure that the only required client can elect to access the documents as we encrypted.

When MongoDB used as Business Application


  1. Require cloud-based services
  2. Need to reduce the cost of Schema migration
  3. Database administrator requirement is less
  4. shading solutions are required.

Adobe, Electronic Arts, Ebay, Cisco, Google, Facebook, etc. These are the big companies using MongoDB as their database programming language.

When MySQL used as Business Application


  1. Very Low budget
  2. Fixed Schema for Databases
  3. Data Security Priority
  4. High Transaction rates requirement

Nasa, US Navy, Youtube, Netflix, Spotify, Uber, Bank of America, etc. These are the big companies around the world using MySQL as their database programming language.

Conclusion


MongoDB and MySQL both have their weaknesses and strengths. If you are data need to support legacy application or multi-row transactions, then the relational database is the right option for your enterprise or company. Perhaps, if you need more flexibility and schema-free options, these both can work with unstructured data, in this case, MongoDB is the right and best choice.MongoDB is also called NoSQL database which is more exceptional and suitable for handle more data.

Author Bio


Anjaneyulu Naini loves pursuing excellence through writing and has a passion for technology. He believes in having a skill or talent is more valuable than having just a degree. He is Currently working as a Content writer at MindMajix.com.



Wednesday, 1 May 2019

Laravel 5.8 - Get Last Inserted ID



If you know how to get last inserted id in Laravel. If you not know then this post will help you to know how can we get last inserted record id in Laravel. Because in this post we have share Laravel tutorial on getting last inserted data id by 4 different method. So, from this post you can learn 4 method by which you can get the value of last inserted id in Laravel. Here we have use Laravel 5.8 framework in which we have describe 4 method by which we can get the value of last inserted id. In Web application development by using Laravel there are many place where we need to get the value of last inserted id value. So, here we have describe 4 different way by which we can get the last inserted id. In place place of web application we want to get last id of inserted record in Laravel application. Below you can find complete step by step process for get last id in Laravel.



Step 1 - Install Laravel 5.8 framework


First we need to download latest version of Laravel, for this we have to write following command in command prompt. It will install latest version of Laravel in you computer.


composer create-project laravel/laravel=5.8 ajax-crud


Step 2 - Make Database Connection


First we need to make database connection, for this we have to open .env file and in that file we have to define mysql database configuration, which we can see below.


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


Step 3 - Create Model


In this step we have to create model, because by using two method in which we need Laravel Eloquen model class. So we need to create model here. For this we have to go in command prompt and write follwing command. It will create LastId.php model file under app folder.


php artisan make:model LastId -m


After creating model file, in this we have to define table column name on which we have to do database operation. So, below you can find LastId.php model file.

app/LastId.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class LastId extends Model
{
    protected $fillable = [
     'first_name', 'last_name'
    ];
}


Above model command has also create database migration file under database/migrations folder. In this file we have to define table column name with data type, which we have add in table. Below you can find migration file code.


<?php

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

class CreateLastIdsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('last_ids', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('last_ids');
    }
}


Now we want to migrate this table defination to mysql database, for this we have to go command prompt and write following command, it will make last_ids table under mysql database.


php artisan migrate


Step 4 - Create Controller


For handle http request we need to make controller in Laravel, for this we have to go command prompt and write following command. It will make LastIdController.php in app/Http/Controllers folder.


php artisan make:controller LastIdController


In this controller file we have make two method. Below you can find two method description.

index() - This is the root method of this controller. It have load sample_form.blade.php file in browser.
getid() - This method has received ajax request for get the last inserted id. Below you can find 4 different method in Laravel by which we can get the value of last inserted id.
Method 1 - insertGetId() - This method has use Laravel Database class for get the value of last inserted id. For this we need to add use DB; line code at the header of this controller. Below you can find sample code of this method, how it has inserted data into database and return value of last inserted id in Laravel.





          $data = array(
       'first_name'  => $request->first_name,
       'last_name'  => $request->last_name
      );

        $last_id = DB::table('last_ids')
         ->insertGetId($data);

     return response()->json(['id' => $result->$last_id]);


Method 2 - lastInsertId() - This is second method by which we can get last inserted id in Laravel. For use this method, first we need to insert data into table by using Laravel Database library, and then after we need to use Laravel Database library getPDO() method with lastInsertID() method and this method will return last inserted id.


$data = array(
       'first_name'  => $request->first_name,
       'last_name'  => $request->last_name
      );

DB::table('last_ids')->insert($data);
$last_id = DB::getPDO()->lastInsertId();

return response()->json(['id' => $last_id]);


Method 3 - create() - This is third method by which we can get last inserted id in Laravel. This is Laravel Eloquent modal class method which has return data in array of object. So, we can get result in array of object by using create() method, and from object we can get last inserted id. For use this method we need to add use App\LastId; this line of code at the header of controller.


$data = array(
       'first_name'  => $request->first_name,
       'last_name'  => $request->last_name
      );

$result = LastId::create($data);

return response()->json(['id' => $result->id]);


Method 4 - save() - This is the 4th method by which we can get last inserted id in Laravel. This save() method is also Laravel Eloquent Modal class method. For use this method. We we need to create object of modal class and in that object we need to add form data as object. And last we have to use save() method. This method has return result in object of an array and from that object of array we can get value of last inserted id in Laravel.


$result = new LastId;
$result->first_name = $request->first_name;
$result->last_name = $request->last_name;
$result->save();

return response()->json(['id' => $result->id]);


By using above 4 method we can get the value of last inserted id in Laravel. After geting value of last inserted id, it will be send to Ajax request in json format. Whole source code of controller you can find below.

app/Http/Controllers/LastIdController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;

use App\LastId;

class LastIdController extends Controller
{
    function index()
    {
     return view('sample_form');
    }

    function getid(Request $request)
    {
     if($request->ajax())
     {
      $data = array(
       'first_name'  => $request->first_name,
       'last_name'   => $request->last_name
      );

            //Method 1
      /*$last_id = DB::table('last_ids')
         ->insertGetId($data);*/

            //Method 2
      /*DB::table('last_ids')->insert($data);
      $last_id = DB::getPDO()->lastInsertId();*/

            //Method 3
      /*$result = LastId::create($data);*/

            //Method 4
      $result = new LastId;
      $result->first_name = $request->first_name;
      $result->last_name = $request->last_name;
      $result->save();

      return response()->json(['id' => $result->id]);
     }
    }
}



Step 5 - Create View File


Below you can find source code of sample_form.blade.php file. This file has been store under resources/views folder. In this file you can find HTML code for form and Ajax jQuery code for submit form data to server script.


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Get Last Inserted ID</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 - Get Last Inserted ID</h3>
     <br />
     <div class="row">
      <div class="col-md-3">

      </div>
      <div class="col-md-6">
     <form method="post" id="sample_form">
      @CSRF
      <div class="form-group">
       <label>First Name</label>
       <input type="text" name="first_name" class="form-control" />
      </div>
      <div class="form-group">
       <label>Last Name</label>
       <input type="text" name="last_name" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="submit" class="btn btn-info" value="Submit" />
      </div>
     </form>
     <div id="last_inserted_id"></div>
    </div>
    <div class="col-md-3">
    </div>
   </div>
  </div>
 </body>
</html>
<script>
$(document).ready(function(){
 $('#sample_form').on('submit', function(event){

  event.preventDefault();
  $.ajax({
   url:"{{ route('last-id/getid') }}",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   success:function(data){
    $('#sample_form')[0].reset();
    $('#last_inserted_id').html('Last Inserted ID - ' + data.id);
   }
  })
 });
});
</script>


Step 6 - Set Route


In Laravel application we need to set route for controller method. For this we have to open routes/web.php file. In this file you have to write following code for set route.


<?php

Route::get('last-id', 'LastIdController@index');

Route::post('last-id/getid', 'LastIdController@getid')->name('last-id/getid');

?>


For learn laravel application, we have to go to command prompt and write following command.


php artisan serve


Above command will start laravel server and it will return base url of your laravel application. For run this last inseted id application we need to write following url.


http://127.0.0.1:8000/last-id




Tuesday, 30 April 2019

How to Append Database Rows to HTML Table using Ajax with PHP



This is one more post on PHP with Ajax and in this post you can find how to Append Last Inserted Data to HTML table by using Ajax with PHP script. So, we do not want to fetch whole table data from mysql database and converted into HTML table and display on web page. In simple terms, if you have use ajax with PHP, then what happen at the time of inserting of data using Ajax with PHP, in PHP script you have first run insert query command and then after you have fetch whole table data from Mysql table and convert into HTML table and send back to Ajax request.

But If you have use Ajax then why you have fetch whole table data again and again on every insert of data. But append last inserted data to existing table. So, when your script has done inserting of data, then last inserting details will be send to Ajax request in JSON format and in Ajax success function that json data will be converted into table row format and by using prepend() method we can append into HTML table. So User will fill lasted submitted data has been store under database and from database that data has been display on web in HTML table format.

Here we have do simple process of Insert data into Mysql table using PHP with Ajax and here by using jQuery which has build table row from Ajax response which has been received in JSON format. So, jQuery has append Ajax result into existing table without refresh of web page. If you have not know how to append ajax return data to HTML table then your doubt will be clear from this post. You can append data from start of the table by using jQuery prepend() method and if you want to append at the end of table then by using jQuery append() method. Below you can find complete source code and online demo also.







Source Code


index.php



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

$query = "SELECT * FROM tbl_sample ORDER BY id DESC";

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

$statement->execute();

$result = $statement->fetchAll();

?>

<html>
 <head>
  <title>How to Use Ajax PHP to Append Last Inserted Data to HTML Tables | Using AJAX to append database rows to HTML tables</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
 </head>
 <body>
  <div class="container">
   <br />
   <br />
   <h2 align="center">How to Use Ajax PHP to Append Last Inserted Data to HTML Tables</h2><br />
   <h3 align="center">Add Details</h3>
   <br />
   <form method="post" id="add_details">
    <div class="form-group">
     <label>First Name</label>
     <input type="text" name="first_name" class="form-control" required />
    </div>
    <div class="form-group">
     <label>Last Name</label>
     <input type="text" name="last_name" class="form-control" required />
    </div>
    <div class="form-group">
     <input type="submit" name="add" id="add" class="btn btn-success" value="Add" />
    </div>
   </form>
   <br />
   <h3 align="center">View Details</h3>
   <br />
   <table class="table table-striped table-bordered">
    <thead>
     <tr>
      <th>First Name</th>
      <th>Last Name</th>
     </tr>
    </thead>
    <tbody id="table_data">
    <?php
    foreach($result as $row)
    {
     echo '
     <tr>
      <td>'.$row["first_name"].'</td>
      <td>'.$row["last_name"].'</td>
     </tr>
     ';
    }
    ?>
    </tbody>
   </table>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $('#add_details').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"insert.php",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function(){
    $('#add').attr('disabled', 'disabled');
   },
   success:function(data){
    $('#add').attr('disabled', false);
    if(data.first_name)
    {
     var html = '<tr>';
     html += '<td>'+data.first_name+'</td>';
     html += '<td>'+data.last_name+'</td></tr>';
     $('#table_data').prepend(html);
     $('#add_details')[0].reset();
    }
   }
  })
 });
 
});
</script>


insert.php



<?php

//insert.php

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

$data = array(
 ':first_name'  => $_POST["first_name"],
 ':last_name'  => $_POST["last_name"]
); 

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

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

if($statement->execute($data))
{
 $output = array(
  'first_name' => $_POST['first_name'],
  'last_name'  => $_POST['last_name']
 );

 echo json_encode($output);
}

?>





Saturday, 27 April 2019

Ajax Form Validation in Codeigniter with JSON



If you not know how to validate form data by using Codeigniter Form validation library by using Ajax and receive response in JSON data type. In this post you can find Form validation in Codeignter by using Ajax jQuery and JSON. For learn Codeigniter Form Validation library with Ajax, here we will make codeigniter ajax contact form for learn this topic.

We have already learn many thing in Codeigniter framework with Ajax. In this post we have share interesting topic on Codeigniter with Ajax and here you can find how to create Ajax jQuery form validation in Codeigniter framework. With help of Codeigniter Form validation library with Ajax, we will received success or error message in JSON format.

Every programmer know validation is a very important part of any web based application or any type of Software process. Because in every web application you can find form like login form, registration form, contact us form comment form etc, so we want to validate form data, if we have not validate form data then it is very dangerous for our web application. If you have use Codeigniter framework for your web based application then Codeigniter has rich form validation library for validate form data, which set server side validation. But server side form data validation has refresh page on every form submission. So, We want to prevent to refresh form, we have to use Ajax with Codeigniter form validation library. Which has been send ajax request to Codeigniter method which will perform validation rules on form data by using Form Validation library. If there is any validation error occur then by using form_error() method it will fetch validation error and store under array and send to back to ajax request in JSON format.

So, Form submission process will be done without refresh of web page. Here you can also find how to submit form in codeigniter by using Ajax without refresh of web page. For learn this topic here we will make contact form with field like name, email address, subject and message. This contact form data will be send to Codeigniter method by using Ajax. In Codeigiter method it will perform different validation rules like required field validation, email format validation by using codeigniter form validation library. And after success of validation rules then it will send response to ajax in json format. Below you can find complete source code of Codeigniter Ajax Form validation.





Source Code


Form_validation.php (Controllers)



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Form_validation extends CI_Controller {

 function index()
 {
  $this->load->view('form_validation');
 }

 function validation()
 {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('name', 'Name', 'required');
  $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
  $this->form_validation->set_rules('subject', 'Subject', 'required');
  $this->form_validation->set_rules('message', 'Message', 'required');
  if($this->form_validation->run())
  {
   $array = array(
    'success' => '<div class="alert alert-success">Thank you for Contact Us</div>'
   );
  }
  else
  {
   $array = array(
    'error'   => true,
    'name_error' => form_error('name'),
    'email_error' => form_error('email'),
    'subject_error' => form_error('subject'),
    'message_error' => form_error('message')
   );
  }

  echo json_encode($array);
 }

}

?>


form_validation.php (Views)



<html>
<head>
    <title>Codeigniter Form Validation using Ajax JSON</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    
</head>
<body>
 <div class="container">
  <br />
  <h3 align="center">Codeigniter Form Validation using Ajax JSON</h3>
  <br />
  <div class="row">
   <div class="col-md-4">

   </div>
   <div class="col-md-4">
    <span id="success_message"></span>
    <form method="post" id="contact_form">
     <div class="form-group">
      <input type="text" name="name" id="name" class="form-control" placeholder="Name" />
      <span id="name_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="text" name="email" id="email" class="form-control" placeholder="Email Address" />
      <span id="email_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="text" name="subject" id="subject" class="form-control" placeholder="Subject">
      <span id="subject_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <textarea name="message" id="message" class="form-control" placeholder="Message" rows="6"></textarea>
      <span id="message_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="submit" name="contact" id="contact" class="btn btn-info" value="Contact Us">
     </div>
    </form>
   </div>
   <div class="col-md-4"></div>
  </div>
 </div>
</body>
</html>
<script>
$(document).ready(function(){

 $('#contact_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"<?php echo base_url(); ?>form_validation/validation",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function(){
    $('#contact').attr('disabled', 'disabled');
   },
   success:function(data)
   {
    if(data.error)
    {
     if(data.name_error != '')
     {
      $('#name_error').html(data.name_error);
     }
     else
     {
      $('#name_error').html('');
     }
     if(data.email_error != '')
     {
      $('#email_error').html(data.email_error);
     }
     else
     {
      $('#email_error').html('');
     }
     if(data.subject_error != '')
     {
      $('#subject_error').html(data.subject_error);
     }
     else
     {
      $('#subject_error').html('');
     }
     if(data.message_error != '')
     {
      $('#message_error').html(data.message_error);
     }
     else
     {
      $('#message_error').html('');
     }
    }
    if(data.success)
    {
     $('#success_message').html(data.success);
     $('#name_error').html('');
     $('#email_error').html('');
     $('#subject_error').html('');
     $('#message_error').html('');
     $('#contact_form')[0].reset();
    }
    $('#contact').attr('disabled', false);
   }
  })
 });

});
</script>





Wednesday, 24 April 2019

Login Registration System with Email Verification in Laravel 5.8



Do you know you can make complete login registration system in Laravel 5.8 with email verification in single artisan command run. If you not know then this post will help you to learn Laravel login authentication and register with step by step guide from scratch. Because Laravel 5.8 has default Login Registration authentication system, so you can make complete login register system in Laravel 5.8 in single run of artisan command run. Here we will discuss step by step process to build Login authentication and register system in Larave 5.8 application. You don't have write any line of code for make login and register system in Laravel 5.8 application. Last release of Laravel 5.8 introduce new features with improvements. So, by using that new features we will make login and register system by using one artisan command like php artisan make:auth. It will create default controllers file, views blade file and set routes for Login and register system.

In this login registration system here we will also covered email verification feature also. So, here we will learn how to verify email address after user has done registration in Laravel 5.8 application. For email verification here we will use new Laravel feature like MustEmailVerify contracts. When user will verify email and it will authenticate and redirect to Laravel user dashboard. If User register and he has not verify his email address then user will not access dashboard of Laravel 5.8 application. In Laravel 5.8 email verification process is very simple and easy to use. We can also modify default Laravel email template and we can create custom email template of email verification, forget password and password reset. If you have use Laravel default Login Registration system then it will reduce your most of time of development.



Install Laravel 5.8


First we want to install Laravel 5.8 fresh set up in out system. For this we have to open terminal and write below command.


composer create-project --prefer-dist laravel/laravel firstApp


Configure .env file


Once you have done install Laravel 5.8 application, in next step we want to configuare .env file for Mysql configuration and email sending configuration.


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



MAIL_DRIVER=smtp
MAIL_HOST=smtpout.secureserver.net
MAIL_PORT=80
MAIL_USERNAME=xxxxx
MAIL_PASSWORD=xxxxx
MAIL_ENCRYPTION=null





Generate Laravel 5.8 Application Key


After .env configuration completed then we have to generate application. For this we have to go command prompt and write following command for genrate laravel application key.


php artisan key:generate


Laravel 5.8 Database Migration


For make Login Register system we have to make User table in Mysql database. Here we will make User table from this Laravel 5.8 application by migrating database. But before migrating database by using command. First we have to open app/providers/AppServiceProvider.php and add two line of code under boot method.


<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }
}

?>


After this we have to go to command prompt and write following command, it will automatic create tables in mysql database and it will also create migration file.


php artisan migrate


After migrating of database, User.php file will be make under app folder. So, we have to open that file and add MustVerifyEmail contracts under the constuctor method. It is for enable email verification.

app/User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable  = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

?>


Laravel 5.8 Authentication


Here we will use Laravel 5.8 default Login Register system by using Laravel 5.8 authentication. For this we have to write following command in command prompt. This command will create controllers, routes and views files for Laravel authentication and registration.


php artisan make:auth


Add Route


For Email Verification, we need to add route under routes/web.php file.


<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes(['verify' => true]); 

Route::get('/home', 'HomeController@index')->name('home');


Add middleware in Controller


After this we need to add middleware in Controller constuctor. For this we have to open app/Http/Controllers/HomeController.php file and add $this->middleware([‘auth’, ‘verified’]); this line under constructor.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'verified']);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }
}

?>


Run Laravel 5.8 application


For run Laravel 5.8 application, we have to go to command prompt and write following command. It will start Laravel 5.8 application and return base url of your Laravel 5.8 application.


php artisan serve


This is complete step by step process for build User Login Register System in Laravel 5.8 application by using default Laravel 5.8 authentication.