Create a DataGrid with PHP MySQLi and jQuery EasyUI

Create a DataGrid with PHP MySQLi and jQuery EasyUI
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Create a DataGrid with PHP MySQLi and jQuery EasyUI</title>
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/color.css">
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/demo/demo.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
</head>
<body>
    <h2>Create a DataGrid with PHP MySQLi and jQuery EasyUI</h2>
    <p>Click the buttons on datagrid toolbar to do crud actions.</p>
    <table id="dg" title="Users Management" class="easyui-datagrid" url="getData.php" toolbar="#toolbar" pagination="true" rownumbers="true" fitColumns="true" singleSelect="true" style="width:100%;height:400px;">
  <thead>
   <tr>
    <th field="first_name" width="50">First Name</th>
    <th field="last_name" width="50">Last Name</th>
    <th field="email" width="50">Email</th>
    <th field="phone" width="50">Phone</th>
   </tr>
  </thead>
 </table>
 <div id="toolbar">
  <div id="tb">
   <input id="term" placeholder="Type keywords...">
   <a href="javascript:void(0);" class="easyui-linkbutton" plain="true" onclick="doSearch()">Search</a>
  </div>
  <div id="tb2" style="">
   <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>
   <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>
   <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyUser()">Remove User</a>
  </div>
 </div>
 <div id="dlg" class="easyui-dialog" style="width:450px" data-options="closed:true,modal:true,border:'thin',buttons:'#dlg-buttons'">
  <form id="fm" method="post" novalidate style="margin:0;padding:20px 50px">
   <h3>User Information</h3>
   <div style="margin-bottom:10px">
    <input name="first_name" class="easyui-textbox" required="true" label="First Name:" style="width:100%">
   </div>
   <div style="margin-bottom:10px">
    <input name="last_name" class="easyui-textbox" required="true" label="Last Name:" style="width:100%">
   </div>
   <div style="margin-bottom:10px">
    <input name="email" class="easyui-textbox" required="true" validType="email" label="Email:" style="width:100%">
   </div>
   <div style="margin-bottom:10px">
    <input name="phone" class="easyui-textbox" required="true" label="Phone:" style="width:100%">
   </div>
  </form>
 </div>
 <div id="dlg-buttons">
  <a href="javascript:void(0);" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="saveUser()" style="width:90px;">Save</a>
  <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close');" style="width:90px;">Cancel</a>
 </div>
 <script type="text/javascript">
 function doSearch(){
  $('#dg').datagrid('load', {
   term: $('#term').val()
  });
 }
   
 var url;
 function newUser(){
  $('#dlg').dialog('open').dialog('center').dialog('setTitle','New User');
  $('#fm').form('clear');
  url = 'addData.php';
 }
 function editUser(){
  var row = $('#dg').datagrid('getSelected');
  if (row){
   $('#dlg').dialog('open').dialog('center').dialog('setTitle','Edit User');
   $('#fm').form('load',row);
   url = 'editData.php?id='+row.id;
  }
 }
 function saveUser(){
  $('#fm').form('submit',{
   url: url,
   onSubmit: function(){
    return $(this).form('validate');
   },
   success: function(response){
    var respData = $.parseJSON(response);
    if(respData.status == 0){
     $.messager.show({
      title: 'Error',
      msg: respData.msg
     });
    }else{
     $('#dlg').dialog('close');
     $('#dg').datagrid('reload');
    }
   }
  });
 }
 function destroyUser(){
  var row = $('#dg').datagrid('getSelected');
  if (row){
   $.messager.confirm('Confirm','Are you sure you want to delete this user?',function(r){
    if (r){
     $.post('deleteData.php', {id:row.id}, function(response){
      if(response.status == 1){
       $('#dg').datagrid('reload');
      }else{
       $.messager.show({
        title: 'Error',
        msg: respData.msg
       });
      }
     },'json');
    }
   });
  }
 }
 </script>
</body>
</html>
//getData.php
<?php
include"dbcon.php"; 
$page = isset($_POST['page']) ? intval($_POST['page']) : 1; 
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10; 
 
$searchTerm = isset($_POST['term']) ? $conn->real_escape_string($_POST['term']) : ''; 
 
$offset = ($page-1)*$rows; 
 
$result = array(); 

$whereSQL = "first_name LIKE '$searchTerm%' OR last_name LIKE '$searchTerm%' OR email LIKE '$searchTerm%' OR phone LIKE '$searchTerm%'"; 
$result = $conn->query("SELECT COUNT(*) FROM tbl_users WHERE $whereSQL"); 
$row = $result->fetch_row(); 
$response["total"] = $row[0]; 

$result = $conn->query( "SELECT * FROM tbl_users WHERE $whereSQL ORDER BY id DESC LIMIT $offset,$rows"); 
 
$users = array(); 
while($row = $result->fetch_assoc()){ 
    array_push($users, $row); 
} 
$response["rows"] = $users; 

echo json_encode($response);
?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
//addData.php
<?php
include"dbcon.php"; 
$response = array( 
    'status' => 0, 
    'msg' => 'Some problems occurred, please try again.' 
); 
if(!empty($_REQUEST['first_name']) && !empty($_REQUEST['last_name']) && !empty( $_REQUEST['email']) && !empty($_REQUEST['phone'])){ 
    $first_name = $_REQUEST['first_name']; 
    $last_name = $_REQUEST['last_name']; 
    $email = $_REQUEST['email']; 
    $phone = $_REQUEST['phone'];
 
    $sql = "INSERT INTO tbl_users(first_name,last_name,email,phone) VALUES ('$first_name','$last_name','$email','$phone')"; 
    $insert = $conn->query($sql); 
 
 if($insert){ 
        $response['status'] = 1; 
        $response['msg'] = 'User data has been added successfully!'; 
    } 
}else{ 
    $response['msg'] = 'Please fill all the mandatory fields.'; 
}
echo json_encode($response); 
?>
//editData.php
<?php
include"dbcon.php"; 
$response = array( 
    'status' => 0, 
    'msg' => 'Some problems occurred, please try again.' 
);
if(!empty($_REQUEST['first_name']) && !empty($_REQUEST['last_name']) && !empty( $_REQUEST['email']) && !empty($_REQUEST['phone'])){ 
    $first_name = $_REQUEST['first_name']; 
    $last_name = $_REQUEST['last_name']; 
    $email = $_REQUEST['email']; 
    $phone = $_REQUEST['phone']; 
     
    if(!empty($_REQUEST['id'])){ 
        $id = intval($_REQUEST['id']); 
         
    
        $sql = "UPDATE tbl_users SET first_name='$first_name', last_name='$last_name', email='$email', phone='$phone' WHERE id = $id"; 
        $update = $conn->query($sql); 
         
        if($update){ 
            $response['status'] = 1; 
            $response['msg'] = 'User data has been updated successfully!'; 
        } 
    } 
}else{ 
    $response['msg'] = 'Please fill all the mandatory fields.'; 
} 
echo json_encode($response); 
?>
//deleteData.php
<?php
include"dbcon.php"; 
$response = array( 
    'status' => 0, 
    'msg' => 'Some problems occurred, please try again.' 
); 
if(!empty($_REQUEST['id'])){ 
    $id = intval($_REQUEST['id']); 
     

    $sql = "DELETE FROM tbl_users WHERE id = $id"; 
    $delete = $conn->query($sql); 
     
    if($delete){ 
        $response['status'] = 1; 
        $response['msg'] = 'User data has been deleted successfully!'; 
    } 
} 
echo json_encode($response);
?>

Create a Progress Bar Data Insert using PHP Mysqli bootstrap and Jquery Ajax

Create a Progress Bar Data Insert using PHP Mysqli bootstrap and Jquery Ajax
<!DOCTYPE html>
<html>
 <head>
  <title>Create a Progress Bar Data Insert using PHP Mysqli bootstrap and Jquery Ajax</title>  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
<script>
 $(document).ready(function(){
 $('#sample_form').on('submit', function(event){
   event.preventDefault();
   var count_error = 0;

   if($('#username').val() == '')
   {
    $('#first_name_error').text('User Name is required');
    count_error++;
   }
   else
   {
    $('#first_name_error').text('');
   }

   if($('#useremail').val() == '')
   {
    $('#last_name_error').text('Email is required');
    count_error++;
   }
   else
   {
    $('#last_name_error').text('');
   }

   if(count_error == 0)
   {
    $.ajax({
   url:"ajax_progressbar.php",
   method:"POST",
   data:$(this).serialize(),
   beforeSend:function()
   {
    $('#save').attr('disabled', 'disabled');
    $('#process').css('display', 'block');
   },
   success:function(data)
   { 
    var percentage = 0;

    var timer = setInterval(function(){
     percentage = percentage + 20;
     progress_bar_process(percentage, timer,data);
    }, 1000);
   }
  })
   }
   else
   {
    return false;
   }
   
  });
  
  function progress_bar_process(percentage, timer,data)
  {
 $('.progress-bar').css('width', percentage + '%');
 if(percentage > 100)
 {
  clearInterval(timer);
  $('#sample_form')[0].reset();
  $('#process').css('display', 'none');
  $('.progress-bar').css('width', '0%');
  $('#save').attr('disabled', false);
  $('#success_message').html(data);
  setTimeout(function(){
   $('#success_message').html('');
  }, 5000);
 }
  }
  
 });
</script>
 </head>
 <body>
  <br />
  <br />
  <div class="container">
   <h1 align="center">Create a Progress Bar Data Insert using PHP Mysqli bootstrap and Jquery Ajax</h1>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Registration</h3>
    </div>
      <div class="panel-body">
       <span id="success_message"></span>
       <form method="post" id="sample_form">
     <div class="form-group">
        <label>User Name</label>
         <input type="text" name="username" id="username" class="form-control" />
         <span id="first_name_error" class="text-danger"></span>
        </div>
  <div class="form-group">
         <label>Email</label>
         <input type="text" name="useremail" id="useremail" class="form-control" />
         <span id="last_name_error" class="text-danger"></span>
        </div>
  <div class="form-group" align="center">
         <input type="submit" name="save" id="save" class="btn btn-info" value="Save" />
        </div>
       </form>
       <div class="form-group" id="process" style="display:none;">
        <div class="progress">
       <div class="progress-bar progress-bar-striped active bg-success" role="progressbar" aria-valuemin="0" aria-valuemax="100" style=""></div>
      </div>
       </div>
      </div>
     </div>
  </div>
 </body>
</html>
//ajax_progressbar.php
<?php
include"dbcon.php"; 
if(isset($_POST["username"]))
{
  $username  = $_POST["username"];
  $useremail  = $_POST["useremail"];
  $sql = "INSERT INTO tbl_user (username, useremail) VALUES ('".$username."','".$useremail."')";
    if ($conn->query($sql) === TRUE) {
     echo "<div class='alert alert-success'>New record created successfully</div>";
     $conn->close();
    } else {
    echo "Error: " . $sql . "<br>" . $conn->error."";
    }
}
?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Add/Remove Input Fields Dynamically with PHP Mysqli and JQuery

Add/Remove Input Fields Dynamically with PHP Mysqli and JQuery
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add/Remove Input Fields Dynamically with bootstrap PHP Mysqli and JQuery</title>
<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>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>    
</head>
<body>
 <script>
$(document).ready(function() {

var MaxInputs       = 8; //maximum input boxes allowed
var InputsWrapper   = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton       = $("#AddMoreFileBox"); //Add button ID

var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added

$(AddButton).click(function (e)  //on add input button click
{
        if(x <= MaxInputs) //max input box allowed
        {
            FieldCount++; //text box added increment
            //add input box
            $(InputsWrapper).append('<div class="row"><p class="col-xs-6"><input type="text" placeholder="Enter your skill" class="form-control skill_list" name="skill[]" id="field_'+ FieldCount +'" value="Enter your skill '+ FieldCount +'"/></p><a href="#" class="btn btn-danger removeclass">×</a></div>');
            x++; //text box increment
        }
return false;
});

$("body").on("click",".removeclass", function(e){ //user click on remove text
        if( x > 1 ) {
                $(this).parent('div').remove(); //remove text box
                x--; //decrement textbox
        }
return false;
})
 $('#submit').click(function(){            
           $.ajax({  
                url:"skill.php",  
                method:"POST",  
                data:$('#add_skills').serialize(),  
                success:function(data)  
                {  
                     $('#resultbox').html(data);  
                     $('#add_skills')[0].reset();  
                }  
           });  
      }); 
});
</script>
<style>
.row {padding:10px;}
</style>
<div class="container">  
                <br />  
                <br />  
                <h2 align="center">Add/Remove Input Fields Dynamically with PHP Mysqli and JQuery</h2><div id="resultbox"></div>  
                <div class="form-group">  
                     <form name="add_skills" id="add_skills">  
                                    <div id="InputsWrapper">
          <div class="row">
                                         <div class="col-xs-6"><input type="text" name="skill[]" placeholder="Enter your skill" class="form-control name_list" /></div>
                                         <div class="col-xs-6"><button type="button" name="add" id="AddMoreFileBox" class="btn btn-success">Add More</button></div>
           </div>
         </div>
         <br/>
                               <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />  
                     </form>  
                </div>  
           </div>  
</body>
</html>
//skill.php
<?php
include"dbcon.php"; 
 $number = count($_POST["skill"]);  
 if($number > 0)  
 {  
      for($i=0; $i<$number; $i++)  
      {  
           if(trim($_POST["skill"][$i] != ''))  
           {  
    $skillname = $_POST["skill"][$i];
    $sql = "INSERT INTO skills (skillname) VALUES ('".$skillname."')";
    if ($conn->query($sql) === TRUE) {
    } else {
    echo "Error: " . $sql . "<br>" . $conn->error."";
    }
    
           }  
      } 
   echo "<p class='btn btn-info' align='center'>New record created successfully</p>";
   $conn->close(); 
 }  
 else  
 {  
      echo "Please Enter Name";  
 } 
?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

HTML5 Inline Edit with jQuery Ajax, PHP & MYSQLi

HTML5 Inline Edit with jQuery Ajax, PHP & MYSQLi
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 Inline Content Editing with jQuery, PHP & MYSQL</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function(){
    var message_status = $("#status");
    $("td[contenteditable=true]").blur(function(){
        var field_userid = $(this).attr("id");
        var value = $(this).text();
  var string = value;
  $.post("ajax_inlineupdate.php", { string: string,field_userid: field_userid}, function(data) {
           if(data != '')
     {
   message_status.show();
   message_status.text(data);
   //hide the message
   setTimeout(function(){message_status.hide()},1000);
     }
        });
    });
});
</script>
<style>
table.zebra-style {
 font-family:"Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
 text-align:left;
 border:1px solid #ccc;
 margin-bottom:25px;
 width:50%
}
table.zebra-style th {
 color: #444;
 font-size: 13px;
 font-weight: normal;
 padding: 10px 8px;
}
table.zebra-style td {
 color: #777;
 padding: 8px;
 font-size:13px;
}
table.zebra-style tr.odd {
 background:#f2f2f2;
}
body {
 background:#fafafa;
}
.container {
 width: 800px;
 border: 1px solid #C4CDE0;
 border-radius: 2px;
 margin: 0 auto;
 height: 1300px;
 background:#fff;
 padding-left:10px;
}
#status { padding:10px; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:90%; }
</style>
</head>
<body>
  <h1>HTML5 Inline Edit with jQuery Ajax, PHP & MYSQLi</h1>
  <div id="status"></div>
<table class="table zebra-style">
    <thead>
      <tr>
        <th>#</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>City</th>
      </tr>
    </thead>
    <tbody>
      <tr class="odd">
        <td>1</td>
        <td id="f:1" contenteditable="true">Michael</td>
        <td id="l:1" contenteditable="true">Holz</td>
        <td id="c:1" contenteditable="true">Olongapo City</td>
      </tr>
      <tr>
        <td>2</td>
        <td id="f:2" contenteditable="true">Paula</td>
        <td id="l:2" contenteditable="true">Wilson</td>
        <td id="c:2" contenteditable="true">California</td>
      </tr>
      <tr class="odd">
        <td>3</td>
        <td id="f:3" contenteditable="true">Antonio</td>
        <td id="l:3" contenteditable="true">Moreno</td>
        <td id="c:3" contenteditable="true">Olongapo City</td>
      </tr>
    </tbody>
 </table>
</body>
</html>
//ajax_inlineupdate.php
<?php
include"dbcon.php"; 
$string  = $_POST['string']; 
$field_userid  = $_POST['field_userid']; 
if ($string==''){
 echo "<p class='btn btn-info' align='center'>Please Insert field</p>";
}else{
 $strings = $field_userid;
 $fields = $strings[0]; 
 if ($fields=='f') {
  $setrs = "fname='$string'"; 
 }elseif ($fields=='l') {
  $setrs = "lname='$string'"; 
 }elseif ($fields=='c') {
  $setrs = "city='$string'"; 
 }else{$setrs = "";} 
 $getid = substr($field_userid, 2); 
 $sql = "UPDATE user SET $setrs WHERE id = '$getid' ";
 if ($conn->query($sql) === TRUE) {
  echo "Record updated successfully";
 } else {
  echo "Error updating record: " . $conn->error;
 }  
} 
?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Jquery Page Scrolling

Jquery Page Scrolling
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Jquery Page Scrolling</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$("document").ready(function() {   
    $('.top-title').click(function(){       
     $('html, body').animate({
      scrollTop: $(".middle").offset().top
     }, 2000);               
     });
    $('.middle-title').click(function(){    
     $('html, body').animate({
      scrollTop: $(".bottom").offset().top
     }, 2000);               
     });
    $('.bottom-title').click(function(){      
     $('html, body').animate({
      scrollTop: $(".top").offset().top
     }, 2000);              
     });
});
</script>
<style>
.top, .middle, .bottom{
 padding:30px;
 }
.top{
 height:600px;
 background-color:#FFC;
 margin-bottom:30px;
 border:2px solid #FF9;
 }
.middle{
 height:600px;
 background-color:#FF9;
 border:2px solid #FF6;
 margin-bottom:30px;
 }
.bottom{
 height:600px;
 background-color:#FF6;
 border:2px solid #FF3;
 margin-bottom:30px;
 } 
.top-title, .middle-title, .bottom-title{
 cursor:pointer;
 margin-top:300px;
 text-align:center;
 text-decoration:underline;
 font-size:32px;
 font-weight:700;} 
</style>
</head>
<body>
<h1>jQuery Page Scrolling</h1>
<div class="main">
<div class="top">
 <div class="top-title">Click Here to go to the middle box</div>
</div>
<div class="middle">
 <div class="middle-title">Click Here to go to the bottom box</div>
</div>
<div class="bottom">
 <div class="bottom-title">Click Here to go to the top box</div>
</div>
</div>
</body>
</html>

Django - URL Mapping

Django - URL Mapping 

Django has his own way for URL mapping and it's done by editing your project url.py file (myproject/url.py). The url.py file looks like −
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
   #Examples
   #url(r'^$', 'myproject.view.home', name = 'home'),
   #url(r'^blog/', include('blog.urls')),

   url(r'^admin', include(admin.site.urls)),
)

When a user makes a request for a page on your web app, Django controller takes over to look for the corresponding view via the url.py file, and then return the HTML response or a 404 not found error, if not found. In url.py, the most important thing is the "urlpatterns" tuple. It’s where you define the mapping between URLs and views. A mapping is a tuple in URL patterns like −

from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
   #Examples
   #url(r'^$', 'myproject.view.home', name = 'home'),
   #url(r'^blog/', include('blog.urls')),

   url(r'^admin', include(admin.site.urls)),
   url(r'^hello/', 'myapp.views.hello', name = 'hello'),
)

Sending Parameters to Views

how to send parameters to views. A classic sample is the article example (you want to access an article via "/articles/article_id").

"myapp/view.py"

from django.shortcuts import render
from django.http import HttpResponse

def hello(request):
   return render(request, "hello.html", {})

def viewArticle(request, articleId):
   text = "Displaying article Number : %s"%articleId
   return HttpResponse(text)

We want to map it in myapp/url.py so we can access it via "/myapp/article/articleId", we need the following in "myapp/url.py" −

from django.conf.urls import patterns, include, url

urlpatterns = patterns('myapp.views',
   url(r'^hello/', 'hello', name = 'hello'),
   url(r'^morning/', 'morning', name = 'morning'),
   url(r'^article/(\d+)/', 'viewArticle', name = 'article'),)

http://127.0.0.1:8000/myapp/article/42/

output : Displaying article number : 42

Suppose we want the list of articles of a month of a year, let's add a viewArticles view. Our view.py becomes −

from django.shortcuts import render
from django.http import HttpResponse

def hello(request):
   return render(request, "hello.html", {})

def viewArticle(request, articleId):
   text = "Displaying article Number : %s"%articleId
   return HttpResponse(text)

def viewArticle(request, month, year):
   text = "Displaying articles of : %s/%s"%(year, month)
   return HttpResponse(text)

The corresponding url.py file will look like −

 
from django.conf.urls import patterns, include, url

urlpatterns = patterns('myapp.views',
   url(r'^hello/', 'hello', name = 'hello'),
   url(r'^morning/', 'morning', name = 'morning'),
   url(r'^article/(\d+)/', 'viewArticle', name = 'article'),
   url(r'^articles/(\d{2})/(\d{4})', 'viewArticles', name = 'articles'),)

http://127.0.0.1:8000/myapp/articles/12/2016/

Displaying articles of : 2016/12

To avoid that, it is possible to link a URL parameter to the view parameter. For that, our url.py will become −

 
from django.conf.urls import patterns, include, url

urlpatterns = patterns('myapp.views',
   url(r'^hello/', 'hello', name = 'hello'),
   url(r'^morning/', 'morning', name = 'morning'),
   url(r'^article/(\d+)/', 'viewArticle', name = 'article'),
   url(r'^articles/(?P\d{2})/(?P\d{4})', 'viewArticles', name = 'articles'),)

Python Django Setting Admin Interface

Python Django - Admin Interface

Django provides a ready-to-use user interface for administrative activities. Django automatically generates admin UI based on your project models.

Starting the Admin Interface

The Admin interface depends on the django.countrib module. To have it working you need to make sure some modules are imported in the INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the myproject/settings.py file.

For INSTALLED_APPS make sure you have −

INSTALLED_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'myapp', #created application myapp folder
)

For MIDDLEWARE_CLASSES −

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Before launching your server, to access your Admin Interface, you need to initiate the database −

C:\myprojectdjango>python manage.py migrate

migrate will create necessary tables or collections depending on your db type, necessary for the admin interface to run.

Create user

C:\myprojectdjango>python manage.py createsuperuser

input username, email address and password
Superuser created succesfully

Now to start the Admin Interface, we need to make sure we have configured a URL for our admin interface. Open the myproject/url.py and you should have something like −
 
from django.conf.urls import patterns, include, url
from django.contrib import admin

from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

Now just run the server.

 C:\myprojectdjango>python manage.py runserver

 And your admin interface is accessible at: http://127.0.0.1:8000/admin/

login using created username and password

Python Django - Install Create project and run

Python Django - Install Create project and run

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Django makes it easier to build better web apps quickly and with less code.

You can download the latest version of Django from the link http://www.djangoproject.com/download 

Windows Installation

C:\>pip install Django==1.9.7
c:\>python -c "import django; print(django.get_version())"

Create a Project
c:\>django-admin startproject myprojectdjango

This will create a "myprojectdjango" folder with the following structure −
myprojectdjango/
   manage.py
   myproject/
      __init__.py
      settings.py
      urls.py
      wsgi.py

manage.py − This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code −
__init__.py − Just for python, treat this folder as package.
settings.py − As the name indicates, your project settings.
urls.py − All links of your project and the function to call. A kind of ToC of your project.
wsgi.py − If you need to deploy your project over WSGI.

Setting Up Your Project
Your project is set up in the subfolder myproject/settings.py. Following are some important options you might need to set −

DEBUG = True

This option lets you set if your project is in debug mode or not. Debug mode lets you get more information about your project's error. Never set it to ‘True’ for a live project. However, this has to be set to ‘True’ if you want the Django light server to serve static files. Do it only in the development mode.

DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.sqlite3',
      'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
      'USER': '',
      'PASSWORD': '',
      'HOST': '',
      'PORT': '',
   }
}

Database is set in the ‘Database’ dictionary. The example above is for SQLite engine. As stated earlier, Django also supports −

MySQL (django.db.backends.mysql)
PostGreSQL (django.db.backends.postgresql_psycopg2)
Oracle (django.db.backends.oracle) and NoSQL DB
MongoDB (django_mongodb_engine)
Before setting any new engine, make sure you have the correct db driver installed.

Now that your project is created and configured make sure it's working −

c:\>myprojectdjango>python manage.py runserver

Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Python function and loop example code

Python Function and Loop Example code
 
#!/usr/bin/python

#A function is created with the def keyword
def function():
    pass
#-------------------------------------------------------   
def printme( str ):
   "This prints a passed string into this function"
   print (str)
   return
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
#-------------------------------------------------------
# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   print ("Values inside the function before change: ", mylist)
   mylist[2]=50
   print ("Values inside the function after change: ", mylist)
   return

# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
#-------------------------------------------------------
# Function definition is here
def printinfo( name, age ):
   "This prints a passed info into this function"
   print ("Name: ", name)
   print ("Age ", age)
   return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
#-------------------------------------------------------

print "1 + 1 =", 1 + 1
print "2 * (2 + 3) =", 2 * (2+3)
print "1.2 / 0.3 =", 1.2 / 0.3
print "5 / 2 =", 5 / 2
# 1 + 1 = 2
# 2 * (2 + 3) = 10
# 1.2 / 0.3 = 4.0
# 5 / 2 = 2

#functions
def square(number):
 sqr_num = number **2
 return sqr_num
 
input_num = 5
output_num = square(input_num)
print "print output", output_num 

#function morethan one input
def returnDifference(n1, n2):
 """Return the difference between two numbers.
 Subtracts n2 from n1."""
 return n1 - n2
print "print output", returnDifference(1,1)
 
def add_two_numbers(num1, num2):
 sum = num1 + num2
 return sum
print "print output", add_two_numbers(1,1)
print "print output", add_two_numbers(1,2) 

#loop
n = 1
while (n < 5):
 print "n =", n
 n = n +1
 print "Loop finished "
 
for n in range(1, 5):
 print"n =", n
 print "Loop finished " 
 
for i in range(0, 4):
 if i == 2:
    break
 print i
print "Finished with i = ", str(i) 

phrase = "it marks the spot"
for letter in phrase:
  if letter == "ks":
    print "yes ks" 
  break
else:
  print "There was no 'X' in the phrase"

tries = 0
while tries < 3:
 password = raw_input("Password: ")
 if password == "ednalan":
     break
 else:
     tries = tries +1
else:
     print "Suspicious activity. The authorities have been alerted."

total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2; # Here total is local variable.
   print ("Inside the function local total : ", total)
   return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )  
#-------------------------------------------------------------------
def add_two_numbers(num1, num2):
    sum = num1 + num2
    return sum
    print(add_two_numbers(1,1)) #2
#---------------------------------------------------------------------
n = 1
while (n < 5):
  print("n =", n)
  n = n + 1
print("Loop finished")    
#---------------------------------------------------------------------
numbers = [22, 34, 12, 32, 4]
sum = 0
i = len(numbers)
while (i != 0):
   i -= 1
   sum = sum + numbers[i]
print "The sum is: ", sum
#---------------------------------------------------------------------
import random
while (True):
   val = random.randint(1, 30)
   print val, # 14 14 30 16 16 20 23 15 17 22
   if (val ==  22):
      break
#---------------------------------------------------------------------
import random
num = 0
while (num < 1000):
   num = num + 1
   if (num % 2) == 0:
      continue
   print num,   
#---------------------------------------------------------------------
import random as rnd
for i in range(10):
   print rnd.randint(1, 10),    # 1 2 5 10 10 8 2 9 7 2

def root(x):
   return x * x
#---------------------------------------------------------------------
def root(x):
   return x * x
a = root(2)
b = root(15)
print a, b  
#---------------------------------------------------------------------
x = 15
def function():
   global x
   x = 45
function()
print x # 45
#---------------------------------------------------------------------
print 4 in (2, 3, 5, 6)
for i in range(25):
   print i, # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#---------------------------------------------------------------------
def gen():
   x = 11
   yield x
it = gen()
print it.next() # 11
#---------------------------------------------------------------------
def showModuleName():
    print __doc__
def getModuleFile():
   return __file__
a = showModuleName()
b = getModuleFile()
print a, b
#---------------------------------------------------------------------
def f():
    """This function prints a message """
    print "Today it is a cloudy day"
print isinstance(f, object) # True
print id(f) # 3077407212
print f.func_doc # This function prints a message 
print f.func_name # f
#---------------------------------------------------------------------
from math import sqrt
def cube(x):
    return x * x * x     
print abs(-1)
print cube(9)
print sqrt(81)
#---------------------------------------------------------------------
def showMessage(msg):
    print msg
def cube(x):
    return x * x * x   
x = cube(3)    
print x # 27
showMessage("Computation finished.") # Computation finished.
print showMessage("Ready.") # Ready.
#---------------------------------------------------------------------
n = [1, 2, 3, 4, 5]
def stats(x):
    mx = max(x)
    mn = min(x)
    ln = len(x)
    sm = sum(x)
    return mx, mn, ln, sm    
mx, mn, ln, sm = stats(n)
print stats(n) # (5, 1, 5, 15)
print mx, mn, ln, sm # 5 1 5 15
#---------------------------------------------------------------------
def C2F(c):
    return c * 9/5 + 32
print C2F(100) # 212
print C2F(0) # 32
print C2F(30) # 86
#---------------------------------------------------------------------
def power(x, y=2):
    r = 1
    for i in range(y):
       r = r * x
    return r
print power(3) # 9
print power(3, 3) #27
print power(5, 5) # 3125
#---------------------------------------------------------------------
def display(name, age, sex):
   print "Name: ", name
   print "Age: ", age
   print "Sex: ", sex
display("Lary", 43, "M") # Name:  Lary Age:  43 Sex:  M
display("Joan", 24, "F") # Name:  Joan Age:  24 Sex:  F


Simple Registration Form using Bootstrap PHP and Mysqli

Simple Registration Form using Bootstrap PHP and Mysqli
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Registration Form using Bootstrap PHP and Mysqli</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style type="text/css">
 body{
  color: #fff;
  font-family: 'Roboto', sans-serif;
  background-image: url(''),linear-gradient(100deg,#18b99b,#b1f056);
 }
    .form-control{
  height: 40px;
  box-shadow: none;
  color: #969fa4;
 }
 .form-control:focus{
  border-color: #5cb85c;
 }
    .form-control, .btn{        
        border-radius: 3px;
    }
 .signup-form{
  width: 400px;
  margin: 0 auto;
  padding: 30px 0;
 }
 .signup-form h2{
  color: #636363;
        margin: 0 0 15px;
  position: relative;
  text-align: center;
    }
 .signup-form h2:before, .signup-form h2:after{
  content: "";
  height: 2px;
  width: 30%;
  background: #d4d4d4;
  position: absolute;
  top: 50%;
  z-index: 2;
 }
 .signup-form h2:before{
  left: 0;
 }
 .signup-form h2:after{
  right: 0;
 }
    .signup-form .hint-text{
  color: #999;
  margin-bottom: 30px;
  text-align: center;
 }
    .signup-form form{
  color: #999;
  border-radius: 3px;
     margin-bottom: 15px;
        background: #f2f3f7;
        box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
        padding: 30px;
    }
 .signup-form .form-group{
  margin-bottom: 20px;
 }
 .signup-form input[type="checkbox"]{
  margin-top: 3px;
 }
 .signup-form .btn{        
        font-size: 16px;
        font-weight: bold;  
  min-width: 140px;
        outline: none !important;
    }
 .signup-form .row div:first-child{
  padding-right: 10px;
 }
 .signup-form .row div:last-child{
  padding-left: 10px;
 }     
    .signup-form a{
  color: #fff;
  text-decoration: underline;
 }
    .signup-form a:hover{
  text-decoration: none;
 }
 .signup-form form a{
  color: #5cb85c;
  text-decoration: none;
 } 
 .signup-form form a:hover{
  text-decoration: underline;
 }
</style> 
</head>
<body>
<div class="signup-form">
    <form action="confirmation.php" method="post" autocomplete="off">
  <h2>Register</h2>
  <p class="hint-text">Create your account. It's free and only takes a minute.</p>
        <div class="form-group">
   <div class="row">
    <div class="col-xs-6"><input type="text" class="form-control" name="first_name" placeholder="First Name" required="required"></div>
    <div class="col-xs-6"><input type="text" class="form-control" name="last_name" placeholder="Last Name" required="required"></div>
   </div>         
        </div>
        <div class="form-group">
         <input type="email" class="form-control" name="email" placeholder="Email" required="required">
        </div>
  <div class="form-group">
            <input type="password" class="form-control" name="password" placeholder="Password" required="required">
        </div>
  <div class="form-group">
            <input type="password" class="form-control" name="confirm_password" placeholder="Confirm Password" required="required">
        </div>        
        <div class="form-group">
   <label class="checkbox-inline"><input type="checkbox" name="agree" required="required"> I accept the <a href="#">Terms of Use</a> & <a href="#">Privacy Policy</a></label>
  </div>
  <div class="form-group">
            <button type="submit" class="btn btn-success btn-lg btn-block">Register Now</button>
        </div>
    </form>
 <div class="text-center">Already have an account? <a href="#">Sign in</a></div>
</div>
</body>
</html>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
//confirmation.php
<?php
include"dbcon.php"; 
$first_name  = $_POST['first_name'];
$last_name  = $_POST['last_name'];
$email  = $_POST['email']; 
$password  = $_POST['password']; 
$sql = "INSERT INTO user (fname, lname, emailadd, pass)
VALUES ('".$first_name."','".$last_name."','".$email."','".$password."')";
if ($conn->query($sql) === TRUE) {
 echo "<h1 align='center'>New record created successfully</h1>";
} else {
 echo "Error: " . $sql . "<br>" . $conn->error."";
}
$conn->close();
?>

Data Table with Add, Edit and Delete Row Using PHP,Mysqli jquery Ajax

Data Table with Add, Edit and Delete Row Using PHP,Mysqli jquery Ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Data Table with Add, Edit and Delete Row Using PHP,Mysqli jquery Ajax</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
    body {
        color: #404E67;
        background: #F5F7FA;
  font-family: 'Open Sans', sans-serif;
 }
 .table-wrapper {
  width: 700px;
  margin: 30px auto;
        background: #fff;
        padding: 20px; 
        box-shadow: 0 1px 1px rgba(0,0,0,.05);
    }
    .table-title {
        padding-bottom: 10px;
        margin: 0 0 10px;
    }
    .table-title h2 {
        margin: 6px 0 0;
        font-size: 22px;
    }
    .table-title .add-new {
        float: right;
  height: 30px;
  font-weight: bold;
  font-size: 12px;
  text-shadow: none;
  min-width: 100px;
  border-radius: 50px;
  line-height: 13px;
    }
 .table-title .add-new i {
  margin-right: 4px;
 }
    table.table {
        table-layout: fixed;
    }
    table.table tr th, table.table tr td {
        border-color: #e9e9e9;
    }
    table.table th i {
        font-size: 13px;
        margin: 0 5px;
        cursor: pointer;
    }
    table.table th:last-child {
        width: 100px;
    }
    table.table td a {
  cursor: pointer;
        display: inline-block;
        margin: 0 5px;
  min-width: 24px;
    }   
 table.table td a.add {
        color: #27C46B;
    }
    table.table td a.edit {
        color: #FFC107;
    }
    table.table td a.delete {
        color: #E34724;
    }
    table.table td i {
        font-size: 19px;
    }
 table.table td a.add i {
        font-size: 24px;
     margin-right: -1px;
        position: relative;
        top: 3px;
    }    
    table.table .form-control {
        height: 32px;
        line-height: 32px;
        box-shadow: none;
        border-radius: 2px;
    }
 table.table .form-control.error {
  border-color: #f50000;
 }
 table.table td .add {
  display: none;
 }
</style>
<script type="text/javascript">
$(document).ready(function(){
 $('[data-toggle="tooltip"]').tooltip();
 var actions = $("table td:last-child").html();
 // Append table with add row form on add new button click
    $(".add-new").click(function(){
  $(this).attr("disabled", "disabled");
  var index = $("table tbody tr:last-child").index();
        var row = '<tr>' +
            '<td><input type="text" class="form-control" name="name" id="txtname"></td>' +
            '<td><input type="text" class="form-control" name="department" id="txtdepartment"></td>' +
            '<td><input type="text" class="form-control" name="phone" id="txtphone"></td>' +
   '<td>' + actions + '</td>' +
        '</tr>';
     $("table").append(row);  
  $("table tbody tr").eq(index + 1).find(".add, .edit").toggle();
        $('[data-toggle="tooltip"]').tooltip();
    });
 
 // Add row on add button click
 $(document).on("click", ".add", function(){
  var empty = false;
  var input = $(this).parents("tr").find('input[type="text"]');
        input.each(function(){
   if(!$(this).val()){
    $(this).addClass("error");
    empty = true;
   } else{
                $(this).removeClass("error");
            }
  });
  var txtname = $("#txtname").val();
  var txtdepartment = $("#txtdepartment").val();
  var txtphone = $("#txtphone").val();
  $.post("ajax_add.php", { txtname: txtname, txtdepartment: txtdepartment, txtphone: txtphone}, function(data) {
   $("#displaymessage").html(data);
  });
  $(this).parents("tr").find(".error").first().focus();
  if(!empty){
   input.each(function(){
    $(this).parent("td").html($(this).val());
   });   
   $(this).parents("tr").find(".add, .edit").toggle();
   $(".add-new").removeAttr("disabled");
  } 
    });
 // Delete row on delete button click
 $(document).on("click", ".delete", function(){
        $(this).parents("tr").remove();
  $(".add-new").removeAttr("disabled");
  var id = $(this).attr("id");
  var string = id;
  $.post("ajax_delete.php", { string: string}, function(data) {
   $("#displaymessage").html(data);
  });
    });
 // update rec row on edit button click
 $(document).on("click", ".update", function(){
  var id = $(this).attr("id");
  var string = id;
        var txtname = $("#txtname").val();
  var txtdepartment = $("#txtdepartment").val();
  var txtphone = $("#txtphone").val();
  $.post("ajax_update.php", { string: string,txtname: txtname, txtdepartment: txtdepartment, txtphone: txtphone}, function(data) {
   $("#displaymessage").html(data);
  });
    });
 // Edit row on edit button click
 $(document).on("click", ".edit", function(){  
        $(this).parents("tr").find("td:not(:last-child)").each(function(i){
   if (i=='0'){
    var idname = 'txtname';
   }else if (i=='1'){
    var idname = 'txtdepartment';
   }else if (i=='2'){
    var idname = 'txtphone';
   }else{} 
   $(this).html('<input type="text" name="updaterec" id="' + idname + '" class="form-control" value="' + $(this).text() + '">');
  });  
  $(this).parents("tr").find(".add, .edit").toggle();
  $(".add-new").attr("disabled", "disabled");
  $(this).parents("tr").find(".add").removeClass("add").addClass("update");
    });
});
</script> 
</head>
<body>
    <div class="container"><p><h1 align="center">Data Table with Add and Delete Row Using PHP,Mysqli jquery</h1><div id="displaymessage"></div></p>
        <div class="table-wrapper">
            <div class="table-title">
                <div class="row">
                    <div class="col-sm-8"><h2>Employee <b>Details</b></h2></div>
                    <div class="col-sm-4">
                        <button type="button" class="btn btn-info add-new"><i class="fa fa-plus"></i> Add New</button>
                    </div>
                </div>
            </div>
   <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Department</th>
                        <th>Phone</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
<?php 
include"dbcon.php"; 
$query_pag_data = "SELECT * from students";
$result_pag_data = mysqli_query($conn, $query_pag_data);
while($row = mysqli_fetch_assoc($result_pag_data)) {
 $student_id=$row['student_id']; 
 $student_name=$row['student_name']; 
 $department=$row['department']; 
 $phone=$row['phone']; 
?>
                    <tr>
                        <td><?php echo $student_name; ?></td>
                        <td><?php echo $department; ?></td>
                        <td><?php echo $phone; ?></td>
                        <td>
       <a class="add" title="Add" data-toggle="tooltip" id="<?php echo $student_id; ?>"><i class="fa fa-user-plus"></i></a>
                            <a class="edit" title="Edit" data-toggle="tooltip" id="<?php echo $student_id; ?>"><i class="fa fa-pencil"></i></a>
                            <a class="delete" title="Delete" data-toggle="tooltip" id="<?php echo $student_id; ?>"><i class="fa fa-trash-o"></i></a>
                        </td>
                    </tr>   
<?php } ?>     
                </tbody>
            </table>
        </div>
    </div>     
</body>
</html>                            
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
<?php
include"dbcon.php"; 
$txtname  = $_POST['txtname'];
$txtdepartment  = $_POST['txtdepartment'];
$txtphone  = $_POST['txtphone'];
if ($txtname==''){
 echo "<p class='btn btn-info' align='center'>Please Insert YOUr name</p>";
}else{ 
 $sql = "INSERT INTO students (student_name, department, phone)
 VALUES ('".$txtname."','".$txtdepartment."','".$txtphone."')";
 if ($conn->query($sql) === TRUE) {
 echo "<p class='btn btn-info' align='center'>New record created successfully</p>";
 } else {
 echo "Error: " . $sql . "<br>" . $conn->error."";
 }
 $conn->close();
} 
?>
<?php
include"dbcon.php"; 
 $id=$_POST['string'];
 $sql = "delete from students where student_id='$id'";
 if ($conn->query($sql) === TRUE) {
  echo "<p class='btn btn-info' align='center'>Record deleted successfully</p>";
 } else {
  echo "Error deleting record: " . $conn->error;
 } 

?>
<?php
include"dbcon.php"; 
$string  = $_POST['string'];
$txtname  = $_POST['txtname'];
$txtdepartment  = $_POST['txtdepartment'];
$txtphone  = $_POST['txtphone'];
if ($txtname==''){
 echo "<p class='btn btn-info' align='center'>Please Insert YOUr name</p>";
}else{
 $sql = "UPDATE students SET student_name='$txtname', department='$txtdepartment', phone='$txtphone' WHERE student_id = '$string' ";
 if ($conn->query($sql) === TRUE) {
  echo "Record updated successfully";
 } else {
  echo "Error updating record: " . $conn->error;
 } 
}
?>

PHP MySQLi Insert Data Into Database

PHP MySQLi Insert Data Into Database
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PHP MySQLi Insert Data Into Database</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testingdb";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST["submit"])){
 $sql = "INSERT INTO students (student_name, student_email, student_city)
 VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";

 if ($conn->query($sql) === TRUE) {
 echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
 } else {
 echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
 }
 $conn->close();
}
?>
<div id="main">
<center>
<h1>Insert data into database using mysqli</h1>
<div id="registration">
<h2>Student's Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123@gmail.com"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="city" required="required" placeholder="Please Enter Your City"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</center>
</div>
<style>
@import url(http://fonts.googleapis.com/css?family=Raleway);
#main{
 width:100%;
 font-family: 'Raleway', sans-serif;
}
h2{
 background-color: #C4F980;
 text-align:center;
 border-radius: 10px 10px 0 0;
 margin: -10px -40px;
 padding: 15px;
}
hr{
 border:0;
 border-bottom:1px solid #ccc;
 margin: 10px -40px;
 margin-bottom: 30px;
}
#registration{
 width:300px;text-align:left;
 border-radius: 10px;
 font-family:raleway;
 border: 2px solid #ccc;
 padding: 10px 40px 25px;
 margin-top: 70px;
}
input[type=text],input[type=email]{
 width:99.5%;
 padding: 10px;
 margin-top: 8px;
 border: 1px solid #ccc;
 padding-left: 5px;
 font-size: 16px;
 font-family:raleway;
}
input[type=submit]{
 width: 100%;
 background-color:#7ECF16;
 color: white;
 border: 2px solid #6BB30F;
 padding: 10px;
 font-size:20px;
 cursor:pointer;
 border-radius: 5px;
 margin-bottom: -12px;
}
</style>
</body>
</html>       

Data Table using Mysqli Database and Bootstrap with Modal Form and pagenation

Data Table using Mysqli Database and Bootstrap with Modal Form
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Data Table using Mysqli Database and Bootstrap with Modal Form</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
    body {
        color: #566787;
  background: #f5f5f5;
  font-family: 'Varela Round', sans-serif;
  font-size: 13px;
 }
 .table-wrapper {
        background: #fff;
        padding: 20px 25px;
        margin: 30px 0;
  border-radius: 3px;
        box-shadow: 0 1px 1px rgba(0,0,0,.05);
    }
 .table-title {        
  padding-bottom: 15px;
  background: #0d2438;
  color: #fff;
  padding: 16px 30px;
  margin: -20px -25px 10px;
  border-radius: 3px 3px 0 0;
    }
    .table-title h2 {
  margin: 5px 0 0;
  font-size: 24px;
 }
 .table-title .btn-group {
  float: right;
 }
 .table-title .btn {
  color: #fff;
  float: right;
  font-size: 13px;
  border: none;
  min-width: 50px;
  border-radius: 2px;
  border: none;
  outline: none !important;
  margin-left: 10px;
 }
 .table-title .btn i {
  float: left;
  font-size: 21px;
  margin-right: 5px;
 }
 .table-title .btn span {
  float: left;
  margin-top: 2px;
 }
    table.table tr th, table.table tr td {
        border-color: #e9e9e9;
  padding: 12px 15px;
  vertical-align: middle;
    }
 table.table tr th:first-child {
  width: 60px;
 }
 table.table tr th:last-child {
  width: 100px;
 }
    table.table-striped tbody tr:nth-of-type(odd) {
     background-color: #fcfcfc;
 }
 table.table-striped.table-hover tbody tr:hover {
  background: #f5f5f5;
 }
    table.table th i {
        font-size: 13px;
        margin: 0 5px;
        cursor: pointer;
    } 
    table.table td:last-child i {
  opacity: 0.9;
  font-size: 22px;
        margin: 0 5px;
    }
 table.table td a {
  font-weight: bold;
  color: #566787;
  display: inline-block;
  text-decoration: none;
  outline: none !important;
 }
 table.table td a:hover {
  color: #2196F3;
 }
 table.table td a.edit {
        color: #FFC107;
    }
    table.table td a.delete {
        color: #F44336;
    }
    table.table td i {
        font-size: 19px;
    }
 table.table .avatar {
  border-radius: 50%;
  vertical-align: middle;
  margin-right: 10px;
 }

    .pagination {
        float: right;
        margin: 0 0 5px;
    }
    .pagination li a {
        border: none;
        font-size: 13px;
        min-width: 30px;
        min-height: 30px;
        color: #999;
        margin: 0 2px;
        line-height: 30px;
        border-radius: 2px !important;
        text-align: center;
        padding: 0 6px;
    }
    .pagination li a:hover {
        color: #666;
    } 
    .pagination li.active a, .pagination li.active a.page-link {
        background: #03A9F4;
    }
    .pagination li.active a:hover {        
        background: #0397d6;
    }
 .pagination li.disabled i {
        color: #ccc;
    }
    .pagination li i {
        font-size: 16px;
        padding-top: 6px
    }
    .hint-text {
        float: left;
        margin-top: 10px;
        font-size: 13px;
    } 
   
 /* Custom checkbox */
 .custom-checkbox {
  position: relative;
 }
 .custom-checkbox input[type="checkbox"] {    
  opacity: 0;
  position: absolute;
  margin: 5px 0 0 3px;
  z-index: 9;
 }
 .custom-checkbox label:before{
  width: 18px;
  height: 18px;
 }
 .custom-checkbox label:before {
  content: '';
  margin-right: 10px;
  display: inline-block;
  vertical-align: text-top;
  background: white;
  border: 1px solid #bbb;
  border-radius: 2px;
  box-sizing: border-box;
  z-index: 2;
 }
 .custom-checkbox input[type="checkbox"]:checked + label:after {
  content: '';
  position: absolute;
  left: 6px;
  top: 3px;
  width: 6px;
  height: 11px;
  border: solid #000;
  border-width: 0 3px 3px 0;
  transform: inherit;
  z-index: 3;
  transform: rotateZ(45deg);
 }
 .custom-checkbox input[type="checkbox"]:checked + label:before {
  border-color: #03A9F4;
  background: #03A9F4;
 }
 .custom-checkbox input[type="checkbox"]:checked + label:after {
  border-color: #fff;
 }
 .custom-checkbox input[type="checkbox"]:disabled + label:before {
  color: #b8b8b8;
  cursor: auto;
  box-shadow: none;
  background: #ddd;
 }
 /* Modal styles */
 .modal .modal-dialog {
  max-width: 400px;
 }
 .modal .modal-header, .modal .modal-body, .modal .modal-footer {
  padding: 20px 30px;
 }
 .modal .modal-content {
  border-radius: 3px;
 }
 .modal .modal-footer {
  background: #ecf0f1;
  border-radius: 0 0 3px 3px;
 }
    .modal .modal-title {
        display: inline-block;
    }
 .modal .form-control {
  border-radius: 2px;
  box-shadow: none;
  border-color: #dddddd;
 }
 .modal textarea.form-control {
  resize: vertical;
 }
 .modal .btn {
  border-radius: 2px;
  min-width: 100px;
 } 
 .modal form label {
  font-weight: normal;
 }
</style> 
<script type="text/javascript">
$(document).ready(function(){
 // Activate tooltip
 $('[data-toggle="tooltip"]').tooltip();
 
 // Select/Deselect checkboxes
 var checkbox = $('table tbody input[type="checkbox"]');
 $("#selectAll").click(function(){
  if(this.checked){
   checkbox.each(function(){
    this.checked = true;                        
   });
  } else{
   checkbox.each(function(){
    this.checked = false;                        
   });
  } 
 });
 checkbox.click(function(){
  if(!this.checked){
   $("#selectAll").prop("checked", false);
  }
 });
    $('#cmdeleteselected').click (function(event) {
  event.preventDefault();
        var selected = new Array();
   $("input:checkbox[name=options]:checked").each(function() {
    selected.push($(this).val());
   });
  var selectedString = selected.join(",");
        $.post("ajaxdeleteselected.php", {selected: selected },
        function(data){
   $('#deleteEmployeeModalselected').modal('hide');
            $('.result').html(data);
        });  
    });
});
</script>
</head>
<body>
<?php 
include"dbcon.php"; 
if(isset($_POST["cmdaddnew"])){
 $sql = "INSERT INTO tblemployees (fullname, emailadd, address, phone)
 VALUES ('".$_POST["fullname"]."','".$_POST["emailadd"]."','".$_POST["address"]."','".$_POST["phone"]."')";
 if ($conn->query($sql) === TRUE) {
 echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
 } else {
 echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
 }
}
$page = (isset($_GET['page']))?$_GET['page']:'';
$editemployee = (isset($_GET['editemployee']))?$_GET['editemployee']:'';
$deleteemployee = (isset($_GET['deleteemployee']))?$_GET['deleteemployee']:'';

if ($deleteemployee==''){
}else{
echo "<script type= 'text/javascript'>$(document).ready(function(){ $('#deleteEmployeeModal').modal() });</script>";
}
if(isset($_POST["cmdelete"])){
   $sql = "DELETE FROM tblemployees WHERE id='$deleteemployee'";
 if ($conn->query($sql) === TRUE) {
  echo "<script type= 'text/javascript'>alert('Record deleted successfully');
  window.location.replace('bootstrap_data_table_with_modal_form.php');</script>";  
 } else {
  echo "<script type= 'text/javascript'>alert('Error deleting record: " . $sql . "<br>" . $conn->error."');</script>"; 
 }
}
if ($editemployee==''){
}else{
 echo "<script type= 'text/javascript'>$(document).ready(function(){ $('#editEmployeeModal').modal() });</script>";
 $results = mysqli_query($conn,"SELECT * FROM tblemployees Where id=$editemployee");
 while($row = mysqli_fetch_array($results))
 {
  $editid = $row["id"];
  $edit_fullname = $row["fullname"];
  $edit_emailadd = $row["emailadd"];
  $edit_address = $row["address"];
  $edit_phone = $row["phone"];
 }
}

if(isset($_POST["cmdedit"])){
   $editname = $_POST["editname"];
   $editemail = $_POST["editemail"];
   $editaddress = $_POST["editaddress"];
   $editphone = $_POST["editphone"];
   $sql = "UPDATE tblemployees SET fullname='$editname', emailadd='$editemail', address='$editaddress', phone='$editphone' WHERE id='$editemployee'";
   if (mysqli_query($conn, $sql)) {
     echo "<script type= 'text/javascript'>alert('Record updated successfully');
  window.location.replace('bootstrap_data_table_with_modal_form.php');</script>";  
   } else {
     echo "<script type= 'text/javascript'>alert('Error updating record: " . $sql . "<br>" . $conn->error."');</script>"; 
   }
}
if ($page==''){
 $page = "1";
}else{
 $page = $_GET['page'];
}
$cur_page = $page;
$page -= 1;
$per_page = 5; 
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
$query_pag_data = "SELECT * from tblemployees LIMIT $start, $per_page";
$result_pag_data = mysqli_query($conn, $query_pag_data);
?>
<div class="container"><div class = "result"></div>
 <p><h1 align="center">Data Table using Mysqli Database and Bootstrap with Modal Form</h1></p>
        <div class="table-wrapper">
            <div class="table-title">
                <div class="row">
                    <div class="col-sm-6">
      <h2>Manage <b>Employees</b></h2>
     </div>
     <div class="col-sm-6">
      <a href="#addEmployeeModal" class="btn btn-success" data-toggle="modal"><i class="material-icons"></i> <span>Add New Employee</span></a>
      <a href="#deleteEmployeeModalselected" class="btn btn-danger" data-toggle="modal"><i class="material-icons"></i> <span>Delete</span></a>      
     </div>
                </div>
            </div>
            <table class="table table-striped table-hover">
                <thead>
     <tr>
      <th>
       <span class="custom-checkbox">
        <input type="checkbox" id="selectAll">
        <label for="selectAll"></label>
       </span>
      </th>
                        <th>Name</th>
                        <th>Email</th>
      <th>Address</th>
                        <th>Phone</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
    while($row = mysqli_fetch_assoc($result_pag_data)) {
     $fullname=$row['fullname']; 
     $emailadd=$row['emailadd']; 
     $address=$row['address']; 
     $phone=$row['phone']; 
    ?>
                    <tr>
      <td>
       <span class="custom-checkbox">
        <input type="checkbox" id="checkbox1" name="options" value="<?php echo $row['id']; ?>">
        <label for="checkbox1"></label>
       </span>
      </td>
                        <td><?php echo $fullname; ?></td>
                        <td><?php echo $emailadd; ?></td>
      <td><?php echo $address; ?></td>
                        <td><?php echo $phone; ?></td>
                        <td>
                            <a href="?editemployee=<?php echo $row['id']; ?>" class="edit" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Edit"></i></a>
                            <a href="?deleteemployee=<?php echo $row['id']; ?>" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete"></i></a>
                        </td>
                    </tr>
    <?php } ?> 
                </tbody>
   </table>
   <div class="clearfix">
<?php
$msg = "";
$query_pag_num = mysqli_query($conn,"SELECT COUNT(*) AS mycount FROM tblemployees" ) or die(mysqli_error($this->dblink));
$res = mysqli_fetch_object($query_pag_num);
$count = $res->mycount;
$no_of_paginations = ceil($count / $per_page);
// ---------------Calculating the starting and endign values for the loop----------------------------------- 
if ($cur_page >= 7) {
    $start_loop = $cur_page - 3;
    if ($no_of_paginations > $cur_page + 3)
        $end_loop = $cur_page + 3;
    else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
        $start_loop = $no_of_paginations - 6;
        $end_loop = $no_of_paginations;
    } else {
        $end_loop = $no_of_paginations;
    }
} else {
    $start_loop = 1;
    if ($no_of_paginations > 7)
        $end_loop = 7;
    else
        $end_loop = $no_of_paginations;
}
//----------------------------------------------------------------------------------------------------------- 
$msg .= "<ul class=\"pagination\">";
// FOR ENABLING THE FIRST BUTTON
if ($first_btn && $cur_page > 1) {
    $msg .= "<li p='1' class='page-item active'><a href='?page=1' class='page-link'>First</a></li>";
} else if ($first_btn) {
    $msg .= "<li p='1' class='page-item' disabled><a href='?page=1'>First</a></li>";
}
// FOR ENABLING THE PREVIOUS BUTTON
if ($previous_btn && $cur_page > 1) {
    $pre = $cur_page - 1;
    $msg .= "<li p='$pre' class='page-item active'><a href='?page=$pre' class='page-link'>Previous</a></li>";
} else if ($previous_btn) {
    $msg .= "<li class='page-item' disabled><a href='?page=1'>Previous</a></li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
    if ($cur_page == $i)
        $msg .= "<li p='$i' class='page-item active'><a href='?page=$i' class='page-link'>{$i}</a></li>";
    else
        $msg .= "<li p='$i' class='page-item'><a href='?page={$i}' class='page-link'>{$i}</a></li>";
}
// TO ENABLE THE NEXT BUTTON
if ($next_btn && $cur_page < $no_of_paginations) {
    $nex = $cur_page + 1;
    $msg .= "<li p='$nex' class='page-item'><a href='?page=$nex' class='page-link'>Next</a></li>";
} else if ($next_btn) {
    $msg .= "<li class='page-item' disabled><a href='#'>Next</a></li>";
}
// TO ENABLE THE END BUTTON
if ($last_btn && $cur_page < $no_of_paginations) {
    $msg .= "<li p='$no_of_paginations' class='page-item'><a href='?page=$no_of_paginations' class='page-link'>Last</a></li>";
} else if ($last_btn) {
    $msg .= "<li p='$no_of_paginations' class='page-item' disabled><a href='?page=$no_of_paginations'>Last</a></li>";
}
$total_string = "<div class=\"hint-text\">Showing <b>" . $cur_page . "</b> out of <b>$no_of_paginations</b> entries</div>";
$msg = $msg . "</ul>";  
echo $total_string;
echo $msg;
?>
            </div>   
  </div>
</div> 

<!-- add Modal HTML -->
 <div id="addEmployeeModal" class="modal fade">
  <div class="modal-dialog">
   <div class="modal-content">
    <form action="" method="post">
     <div class="modal-header">      
      <h4 class="modal-title">Add Employee</h4>
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
     </div>
     <div class="modal-body">     
      <div class="form-group">
       <label>Name</label>
       <input type="text" name="fullname" class="form-control" required>
      </div>
      <div class="form-group">
       <label>Email</label>
       <input type="email" name="emailadd" class="form-control" required>
      </div>
      <div class="form-group">
       <label>Address</label>
       <textarea class="form-control" name="address" required></textarea>
      </div>
      <div class="form-group">
       <label>Phone</label>
       <input type="text" name="phone" class="form-control" required>
      </div>     
     </div>
     <div class="modal-footer">
      <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
      <input type="submit" class="btn btn-success" name="cmdaddnew" value="Add">
     </div>
    </form>
   </div>
  </div>
 </div> 
 <!-- Edit Modal HTML -->
 <div id="editEmployeeModal" class="modal fade">
  <div class="modal-dialog">
   <div class="modal-content">
    <form name="frmedit" action="" method="post">
     <div class="modal-header">      
      <h4 class="modal-title">Edit Employee</h4>
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
     </div>
     <div class="modal-body">     
      <div class="form-group">
       <label>Name</label>
       <input type="text" name="editname" value="<?php echo $edit_fullname; ?>" class="form-control" required>
      </div>
      <div class="form-group">
       <label>Email</label>
       <input type="email" name="editemail" value="<?php echo $edit_emailadd; ?>" class="form-control" required>
      </div>
      <div class="form-group">
       <label>Address</label>
       <textarea class="form-control" name="editaddress" required><?php echo $edit_address; ?></textarea>
      </div>
      <div class="form-group">
       <label>Phone</label>
       <input type="text" name="editphone" value="<?php echo $edit_phone; ?>" class="form-control" required>
      </div>     
     </div>
     <div class="modal-footer">
      <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
      <input type="submit" name="cmdedit" class="btn btn-info" value="Save">
     </div>
    </form>
   </div>
  </div>
 </div>
 
 <!-- Delete Modal HTML -->
 <div id="deleteEmployeeModal" class="modal fade">
  <div class="modal-dialog">
   <div class="modal-content">
    <form name="frmdelete" action="" method="post">
     <div class="modal-header">      
      <h4 class="modal-title">Delete Employee</h4>
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
     </div>
     <div class="modal-body">     
      <p>Are you sure you want to delete these Records?</p>
      <p class="text-warning"><small>This action cannot be undone.</small></p>
     </div>
     <div class="modal-footer">
      <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
      <input type="submit" name="cmdelete" class="btn btn-danger" value="Delete">
     </div>
    </form>
   </div>
  </div>
 </div>
 <div id="deleteEmployeeModalselected" class="modal fade">
  <div class="modal-dialog">
   <div class="modal-content">
    <form name="frmdelete" action="" method="post">
     <div class="modal-header">      
      <h4 class="modal-title">Delete Selected Employee</h4>
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
     </div>
     <div class="modal-body">     
      <p>Are you sure you want to all the selected delete Records?</p>
      <p class="text-warning"><small>This action cannot be undone.</small></p>
     </div>
     <div class="modal-footer">
      <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
      <a href="#" id="cmdeleteselected" class="btn btn-danger">Delete</a>
     </div>
    </form>
   </div>
  </div>
 </div>
</body>
</html>      
//ajaxdeleteselected.php
<?php
include"dbcon.php"; 
$selected  = $_POST['selected'];
foreach ($selected as $value) {
 $sql = "DELETE FROM tblemployees WHERE id='$value'";
 if ($conn->query($sql) === TRUE) {
  echo "Record deleted successfully $value <br/>";  
 } else {
  echo "Error deleting record: " . $sql . "<br>" . $conn->error."'"; 
 } 

}
?>

Bootstrap Subscribe Newsletter Form inside Modal

Bootstrap Subscribe Newsletter Form inside Modal
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap Subscribe Newsletter Form inside Modal</title>
<link href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<style type="text/css">
    body {
  font-family: 'Varela Round', sans-serif;
 } 
 .modal-newsletter { 
  color: #999;
  font-size: 15px;
 }
 .modal-newsletter .modal-content {
  padding: 40px;
  border-radius: 0;  
  border: none;
 }
 .modal-newsletter .modal-header {
  border-bottom: none;   
        position: relative;
  text-align: center;
  border-radius: 5px 5px 0 0;
 }
 .modal-newsletter h4 {
  color: #000;
  text-align: center;
  font-size: 30px;
  margin: 0 0 25px;
  font-weight: bold;
  text-transform: capitalize;
 }
 .modal-newsletter .close {
  background: #c0c3c8;
  position: absolute;
  top: -15px;
  right: -15px;
  color: #fff;
  text-shadow: none;
  opacity: 0.5;
  width: 22px;
  height: 22px;
  border-radius: 20px;
  font-size: 16px;
 }
 .modal-newsletter .close span {
  position: relative;
  top: -1px;
 }
 .modal-newsletter .close:hover {
  opacity: 0.8;
 }
 .modal-newsletter .form-control, .modal-newsletter .btn {
  min-height: 46px;
  border-radius: 3px; 
 }
 .modal-newsletter .form-control {
  box-shadow: none;
  border-color: #dbdbdb;
 }
 .modal-newsletter .form-control:focus {
  border-color: #19bc9c;
  box-shadow: 0 0 8px rgba(114, 101, 234, 0.5);
 }
    .modal-newsletter .btn {
        color: #fff;
        border-radius: 4px;
  background: #19bc9c;
  text-decoration: none;
  transition: all 0.4s;
        line-height: normal;
  padding: 6px 20px;
  min-width: 150px;
        border: none;
    }
 .modal-newsletter .btn:hover, .modal-newsletter .btn:focus {
  background: #4e3de4;
  outline: none;
 }
 .modal-newsletter .input-group {
  margin: 30px 0 15px;
 }
 .hint-text {
  margin: 100px auto;
  text-align: center;
 }
</style>
<script type="text/javascript">
 $(document).ready(function(){
  $("#myModal").modal('show');
 });
</script>
<div id="myModal" class="modal fade">
 <div class="modal-dialog modal-newsletter">
  <div class="modal-content">
   <form action="confirmation.php" method="post">
    <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span>×</span></button>
    </div>
    <div class="modal-body text-center">
     <h4>Subscribe to our newsletter</h4> 
     <p>Sugnup for our weekly newsletter to get the latest news, updates and amazong offers delivered direcly in your inbox.</p>
     <div class="input-group">
      <input type="email" class="form-control" placeholder="Enter your email" required>
      <span class="input-group-btn">
       <input type="submit" class="btn btn-primary" value="Subscribe">
      </span>
     </div>
    </div>
   </form>   
  </div>
 </div>
</div>
<p class="hint-text"><strong>Note:</strong> Refresh the page or run the code to reload the modal.</p>
</body>
</html>

PHP Month Array List Select Box Live-search

PHP Month Array List Select Box Live-search











<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Month Array List Select Box Live-search</title>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
      <h2>PHP Month Array List Select Box Live-search</h2>
      <p>This uses <a href="https://silviomoreto.github.io/bootstrap-select/">https://silviomoreto.github.io/bootstrap-select/</a></p>
      <hr />
    </div>
<?php
$lang_Date = array(
 'Jan'   =>'January',
 'Feb'   =>'February',
 'Mar'   =>'March',
 'Apr'   =>'April',
 'May'   =>'May',
 'June'   =>'June',
 'July'   =>'July',
 'August'  =>'August',
 'Sep'  =>'September',
 'Oct'  =>'October',
 'Nov'  =>'November',
 'Dec'  =>'December',
); 
?>
    <div class="row-fluid">
      <select class="selectpicker" data-show-subtext="true" data-live-search="true">
   <?php
    foreach ($lang_Date as $key=>$value){
  $selected = ($key==$function)?" Selected=\"Selected\"": "";
  echo "<option data-subtext=\"$key\" $selected > $value </option>";
    }
    ?>
      </select>
      <span class="help-inline">Try searching for November</span>
    </div>
  </div>
</body>
</html>

How to create a Jquery Ajax Mysqli Pagenation

Jquery Ajax Pagenation

Create Database table

CREATE TABLE IF NOT EXISTS `paginate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) NOT NULL,
  `message` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ; 
 
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jquery ajax pagenation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $("#results").load("fetch_pages.php", {'page':1} ); //initial page number to load
 $(".paginate_click").click(function (e) {
  $("#results").prepend('<div class="loading-indication"><img src="img/ajax-loader.gif" /> Loading...</div>');
  var page_num = $(this).text(); //get page number from the clicked element 
  $('.paginate_click').removeClass('active'); //remove any active class
  //post page number and load returned data into result element
  $("#results").load("fetch_pages.php", {'page': page_num}, function(){
  });
  $(this).addClass('active'); //add active class to currently clicked element
  return false; //prevent going to herf link
 }); 
});
</script>
</head>
<body>
<?php
include("config.inc.php");
$results = mysqli_query($connecDB,"SELECT COUNT(*) FROM paginate");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page); 
//create pagination
if($pages > 1)
{
 $pagination = '';
 $pagination .= '<ul class="paginate">';
 for($i = 1; $i<$pages; $i++)
 {
  $pagination .= '<li><a href="#" class="paginate_click">'.$i.'</a></li>';
 }
 $pagination .= '</ul>';
} 
?>
<p><h1 align="center">How to create a Jquery Ajax Pagenation</h1></p>
<div id="results"></div>
<?php echo $pagination; ?>
<style>
.paginate {
 padding: 0px;
 margin: 0px;
 height: 30px;
 display: block;
 text-align: center;
}
.paginate li {
 display: inline-block;
 list-style: none;
 padding: 0px;
 margin-right: 1px;
 width: 30px;
 text-align: center;
 background: #4CC2AF;
 line-height: 25px;
}
.paginate .active {
 display: inline-block;
 list-style: none;
 padding: 0px;
 margin-right: 1px;
 width: 30px;
 text-align: center;
 line-height: 25px;
 background-color: #666666;
}
.paginate li a{
 color:#FFFFFF;
 text-decoration:none;
}
#results{
font: 12px Arial, Helvetica, sans-serif;
width: 400px;
margin-left: auto;
margin-right: auto;
}
.page_result{
 padding: 0px;
}
.page_result li{
 background: #E4E4E4;
 margin-bottom: 5px;
 padding: 10px;
 font-size: 12px;
 list-style: none;
}
.page_result .page_name {
font-size: 14px;
font-weight: bold;
margin-right: 5px;
}
#results .loading-indication{
 background:#FFFFFF;
 padding:10px;
 position: absolute;
}
</style>
</body>
</html>
//config.inc.php
<?php
$db_username = 'root';
$db_password = '';
$db_name = 'test';
$db_host = 'localhost';
$item_per_page = 5;

$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
?>
//fetch_pages.php
<?php
include("config.inc.php"); 
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range. 
$results = mysqli_query($connecDB,"SELECT id,name,message FROM paginate ORDER BY id DESC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
 echo '<li id="item_'.$row["id"].'"><span class="page_name">'.$row["name"].'</span><span class="page_message">'.$row["message"].'</span></li>';
}
echo '</ul>';
?>