Saturday 26 December 2015

Codeigniter Categories sub categories dictionary

Some times you want categoriesOr i can say that a dictionary which needs to be fetch from mysql , there for all links , content will be fetch from database mysql by creating a singel view file with support of jQuery for processing menus. There will be your Administration OR Admin panelwho will create these categories , sub categories.
 
1.Your Controller functions will goes like below.
defined('BASEPATH') OR exit('No direct script access allowed');
class School extends MY_Controller {
public function __construct() {
parent::__construct();
}
public function get_dictionary() {
$this->load->model('schools');
$this->load->model('trading_tools');
$data['meta_title'] = 'School';
$data['meta_keywords'] = 'School';
$data['meta_desc'] = 'School';
$data['signup_signin_model'] = 'root/signin_up_model_html';
$parent_slug = trim($this->uri->segment(2));
$child_slug = trim($this->uri->segment(3));
if (isset($child_slug) && $child_slug != '') {
$data = array($child_slug);
$where = 'slug_name';
$data['school_info'] = $this->schools->get_records_where_in('schools_category', $where, $data);
} else {
$data['school_info'] = $this->schools->get_school_info($parent_slug);
}
$menu = $this->trading_tools->get_items();
$data['side_bar_menu'] = $this->buildMenu(0, $menu);
$data['loginheader'] = '';
$data['top_header'] = 'root/top_header';
$data['top_menu'] = 'root/top_menu';
$data['parent_slug_name'] = $parent_slug;
$data['child_slug_name'] = $child_slug;
if ($parent_slug != 'glossary') {
$data['main'] = 'root/school_child';
} else {
$data['main'] = 'root/school_glossary';
}
$data['footer'] = 'root/footer';
$this->load->vars($data);
$this->load->view($this->template);
}
public function buildMenu($parent, $menu) {
$html = "";
if (isset($menu['parent_menus'][$parent])) {
if ($parent <= 0)
$html .= "<ul class='nav nav-pills nav-stacked' style='background:#E9E9E9;'>";
else
$html.= '<ul class="dropdown-menu">';
$countfor_active = 0;
foreach ($menu['parent_menus'][$parent] as $menu_id) {
$li_parentclass = '';
$ul_inside_li = '<ul class="dropdown-menu ' . $menu['menus'][$menu_id]['slug_name'] . '>';
if ($countfor_active == 0) {
$li_parentclass = 'dropdown ' . $menu['menus'][$menu_id]['slug_name'] . '';
}
if (!isset($menu['parent_menus'][$menu_id])) {
$html .= "<li class='" . $li_parentclass . "'>
<a href='" . $menu['menus'][$menu_id]['page_link'] . "'>
" . $menu['menus'][$menu_id]['category_name'] . "</a></li>";
}
if (isset($menu['parent_menus'][$menu_id])) {
$html .= "<li class='" . $li_parentclass . "'>
<a href='" . $menu['menus'][$menu_id]['page_link'] . "'> <i
class='fa fa-angle-right pull-right'></i>
" . $menu['menus'][$menu_id]['category_name'] . "</a>";
$html .= $this->buildMenu($menu_id, $menu);
$html .= "</li>";
}
}
$html .= "</ul>";
}
return $html;
}
}
2. Basically i am using two views filesbecause layout OR html is different for both. One view file will contain Dictionary (school_glossary) and sencond view (school_child) file will contain simple content to display.
 
A) school_glossary View
<div class="l-main-container">
<div class="b-breadcrumbs f-breadcrumbs">
<div class="container">
<ul>
<li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown"
href="#"><i class="fa fa-home"></i>Home</a></li>
<li><i class="fa fa-angle-right"></i><a href="#">Forex Tools</a></li>
<li><i class="fa fa-angle-right"></i><span>Forex School</span></li>
</ul>
</div>
</div>
<div class="l-inner-page-container">
<div class="container">
<div class="row">
<div class="col-md-9 col-md-push-3">
<div class="b-shortcode-example">
<div class="b-tabs f-tabs j-tabs b-tabs-reset ui-tabs ui-widget ui-widget-content ui-corner-all">
<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix
ui-widget-header ui-corner-all" role="tablist">
<?php if (count($school_info) > 0) { ?>
<?php
$alphabet = array('A'=>'glossary-a','B'=>'glossary-b','C'=>'glossary-c','D'=>'glossary-d',
'E'=>'glossary-e','F'=>'glossary-f','G'=>'glossary-g','H'=>
'glossary-h','I'=>'glossary-i','J'=>'glossary-j','K'=>'glossary-k',
'L'=>'glossary-l','M'=>'glossary-m','N'=>'glossary-n','O'=>
'glossary-o','P'=>'glossary-p','Q'=>'glossary-q','R'=>'glossary-r','S'=>'glossary-s'
,'T'=>'glossary-t','U'=>'glossary-u','V'=>'glossary-v','W'=>'glossary-w',
'X'=>'glossary-x','Y'=>'glossary-y','Z'=>'glossary-z');
foreach ($school_info as $key => $value) {?>
<li class="ui-state-default ui-corner-top" role="tab" tabindex="-1"
aria-controls="tabs-21" aria-labelledby="ui-id-1" aria-selected="false" aria-expanded="false">
<a href="#tabs-<?php echo $school_info[$key]->s_category_id;?>"
class="ui-tabs-anchor" role="presentation" tabindex="-1"
id="ui-id-<?php echo $school_info[$key]->s_category_id;?>">
<?php foreach ($alphabet as $al => $alp) {?>
<?php if($alp==$school_info[$key]->slug_name){ ?>
<?php echo $al; ?>
<?php }?>
<?php }?>
</a>
</li>
<?php } ?>               
<?php }?>
</ul>
<div class="b-tabs__content">
<?php if (count($school_info) > 0) { ?> 
<?php foreach ($school_info as $key => $value) {?>
<div id="tabs-<?php echo $school_info[$key]->s_category_id;?>"
aria-labelledby="ui-id-<?php echo $school_info[$key]->s_category_id;?>"
class="ui-tabs-panel ui-widget-content ui-corner-bottom" role="tabpanel" 
aria-hidden="true" style="display: none;">
<?php echo html_entity_decode($school_info[$key]->page_body); ?>
</div>
<?php }?>
<?php }?> 
</div>
</div>
</div>
</div>
<div class="visible-xs-block visible-sm-block b-hr"></div>
<div class="col-md-3 col-md-pull-9">
<?php if (isset($side_bar_menu)) { ?>
<?php echo $side_bar_menu; ?>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
var p_slug_name=".<?php echo $parent_slug_name;?>";
$(".nav").find(p_slug_name).addClass('active');
});
</script>
B) school_child View
<div class="l-main-container">
<div class="b-breadcrumbs f-breadcrumbs">
<div class="container">
<ul>
<li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown"
href="#"><i class="fa fa-home"></i>Home</a></li>
<li><i class="fa fa-angle-right"></i><a href="#">Forex Tools</a></li>
<li><i class="fa fa-angle-right"></i><span>Forex School</span></li>
</ul>
</div>
</div>
<div class="l-inner-page-container">
<div class="container">
<div class="row">  
<?php if (count($school_info) > 0) { ?>
<div class="col-md-9 pull-right"><h4><?php echo $school_info[0]->category_name;?></h4></div>
<?php } ?>
<div class="col-md-9 col-md-push-3">
<div class="b-blog-listing__block">
<div class="b-blog-listing__block-top"> </div>
<div class="b-infoblock-with-icon b-blog-listing__infoblock">
<div class="b-infoblock-with-icon__info f-infoblock-with-icon__info">
<?php if (count($school_info) > 0) { ?>
<?php echo html_entity_decode($school_info[0]->page_body); ?>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="visible-xs-block visible-sm-block b-hr"></div>
<div class="col-md-3 col-md-pull-9">
<?php if (isset($side_bar_menu)) { ?>
<?php echo $side_bar_menu; ?>
<?php } ?> 
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
var p_slug_name=".<?php echo $parent_slug_name;?>";
$(".nav").find(p_slug_name).addClass('active');
});
</script>
3. Your model function will goes like below
class Schools extends CI_Model {
function __construct() {
// Call the Model constructor
parent::__construct();
$this->load->library('session');
$this->load->database();
}
function get_school_info($parent_slug){
$q_school="select * from cbf_schools_category where parentid =(select s_category_id
from cbf_schools_category where slug_name='".$parent_slug."')";
$query=$this->db->query($q_school);
if ($query->num_rows() > 0)
return $query->result();
else
$q_get_main="select * from cbf_schools_category where slug_name='".$parent_slug."'";
$query1=$this->db->query($q_get_main);
return $query1->result();
}
function get_records_where_in($table, $where, $data) {
$this->db->where_in($where, $data);
$query = $this->db->get($table);
if ($query->num_rows() > 0)
return $query->result();
else
return NULL;
}
}
4. You will need to define a routes in your routes.php
$route['school/(:any)'] = 'school/get_dictionary/$1';
5. Your Mysql table goes like below which will contain parent , child relationship in single table.

Monday 30 November 2015

Install and Run Tomcat windows

I am explaining every step to run tomcat in window and how to setup your projects and running Servlets.

1. Install JDK before installing tomcat.

  a) I installed JDK1.6.0 onC:\Java\jdk1.6.0

NOTE: Do not installed JDK under C:\Program Files. I just faced problem after setting my
environment variable on Window Xp.

2. Download the latest version of tomcat.
tomcat.apache.org , i downloaded Apache Tomcat 7.0.65.I rename downloaded folder to "apache-tomcat" and placed it at E:\apache-tomcat.Go to "Start" --> "My Computer" --> Right click--> "Property"--> Click "Advance Tab" --> "Environment Variables" --> Opens a window where you have to create new Environment Variables As Written Below
/* Under User Variable click New */
Variable Name CATALINA_HOME
Variable Value E:\apache-tomcat , Press ok
Variable Name JAVA_HOME
Variable Value C:\Java\jdk1.6.0, Press ok
Variable Name JAVA_HOME
Variable Value C:\Java\jdk1.6.0, Press ok
Variable Name PATH
Variable Value C:\Java\jdk1.6.0\bin, Press ok
// Under System Variable click New
Variable Name CALSSPATH
Variable Value C:\Java\jdk1.6.0\bin;E:\apache-tomcat\lib\servlet-api.jar, Press ok
3. Now We have to edit configuration files E:\apache-tomcat\conf folder
Open file context.xml find line/xml tag <Context>
and replace by <Context reloadable="true">
<servlet>...</servlet> inside this tag find
<param-value>false</param-value> 
and replace with <param-value>true</param-value>
Open file tomcat-users.xml and placed below code inside<tomcat-users>...</tomcat-users>
<role rolename="manager-gui"/>
<role rolename="admin-gui"/>
<user username="boy108zon" password="boy108zon" roles="manager-gui,admin-gui"/>
4.Restart your computer. After above steps configuration. Lets create a new project.

1. I created a folder called store in E:\apache-tomcat\webapps\
2. Create Structure under
store(Project Folder) ---> WEB-INF(DIR) --> classes(DIR) , web.xml (FILE)
classes(DIR)-->HelloWorld.java (File)
3. Placed below xml code in web.xml created as above
  <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
   <web-app>
    <servlet>
     <servlet-name>HelloWorld</servlet-name>
     <servlet-class>HelloWorld</servlet-class>
    </servlet>
    <servlet-mapping>
     <servlet-name>HelloWorld</servlet-name>
     <url-pattern>/</url-pattern>
    </servlet-mapping>
  </web-app>
4. Open http://localhost:8080/ You can see Tomcat Statup Page , you can click on Mange App it will ask you to enter username and password , As you putted OR placed in tomcat-users.xml.
 
Here you can see list of Application running or deploy. if you further check our created application also visible to this list , you can Start , Stop , Reload , Undeploy your application here. Click on start so that our created application can be start.
 
5. That's all , Now open http://localhost:8080/store/ and you will see your HelloWorld Running.

Saturday 28 November 2015

Carousel slider codeigniter mysql

You may also see the post here http://yourlearn.in/posts/view/1/bootstrap-carousel-thumbnail-slider and know and read much more about it.

 
 
 
If you want to implement Bootstrap Carousel Thumbnail Slider with Codeigniter, follow the steps
1.Your html file or you can say your view file will goes like below.
  <!DOCTYPE html>
  <html lang="en">
  <head>
   <title>Bootstrap Example</title>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
   <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
   <style>
    .carousel-inner > .item > img,
    .carousel-inner > .item > a > img {
     width: 70%;
     margin: auto;
    }
   </style>
  </head>
 <body>
 <div id="container"> 
   <div id="slider-property" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <?php echo $indicators; ?>
    </ol>

   <!-- Wrapper for slides -->
   <div class="carousel-inner" role="listbox">
      <?php echo $slides; ?>
   </div>

  <!-- Left and right controls -->
   <a class="left carousel-control" href="#slider-property" role="button" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
   </a>
   <a class="right carousel-control" href="#slider-property" role="button" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
   </a>
  </div>
  </div>
   </div>
 </body>
 </html>
2. Your controller function will goes like below
  class Welcome extends CI_Controller {
        public function index(){
         }    
    public function get_all_images(){  
      $this->load->model('carsol'); 
      $query = $this->carsol->get_all_images();
     $count = count($query);
     $indicators = '';
      $slides = '';
      $counter = 0;  
      foreach($query AS $key => $value){
          $image = $query[$key]['theme_thumb'];
          $title = $query[$key]['theme_title'];
          if ($counter == 0) {
            $indicators .= '<li data-target="#slider-property" data-slide-to="' . $counter . '" 
            class="active"></li>';
            $slides .= '<div class="item active">
            <img src="http://localhost/CI2.1.4/images/thumbnail/' . $image . '" alt="' . $title . '"/>
            </div>';
          } else {
            $indicators .= '<li data-target="#slider-property" 
            data-slide-to="' . $counter . '"></li>';
            $slides .= '<div class="item">
            <img src="http://localhost/CI2.1.4/images/thumbnail/' . $image . '" alt="' . $title . '"/>
            </div>';
          }
          $counter=$counter+1;
      }
      $data['indicators'] = $indicators;
      $data['slides'] = $slides;
      $this->load->view('carsol', $data);   
    }       
 }
3. Your model function will goes like below
  class Carsol extends CI_Model {
   function __construct() {
     // Call the Model constructor
      parent::__construct();
     $this->load->database();
   }
   function get_all_images(){
     $query = $this->db->query("SELECT * FROM theme_themes where category_id =3 limit 4");
     return $query->result_array();
 }
}

Tuesday 24 November 2015

Multiple records delete datatables ajax

If you want to implement add bulk action like Export CSV , Removing all , single records , Export seleted records to excel and adding filters like days filter to data tables listings using ajax approch 1. You need to include required jQuery for datatables , ajax processing.
<script src="<?php echo base_url(); ?>assets/js/jquery-1.11.0.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery.dataTables.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/dataTables.bootstrap.js"></script>
<script src="<?php echo base_url();?>assets/js/datatables/responsive/js/datatables.responsive.js">
</script>
<script src="<?php echo base_url(); ?>assets/js/datatables/jquery.dataTables.columnFilter.js">
</script>
2. Your html source file or you can say your view file will goes like below.
<h3 class="page-title">Accounts</h3>
<div class="panel panel-primary" data-collapsed="0">
<div class="col-sm-12">
<div class="panel-body">
<form id="Gexcel" name="Gexcel" method="POST" action="<?php echo base_url(); ?
>accounts/create_document">
<input type="hidden" name="aidds" id="aidds" ><input type="hidden" name="atype" id="atype" value="da" >
</form>
<table id="demo_account_listing" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th class="no-sort"></th>
<th class="trigger_reload">Sr No</th>
<th>ID</th>
<th>Date</th>
<th class="no-sort">Days Left</th>
<th>Name</th>
<th>Email Address</th>
<th>Country</th>
<th>Phone</th>
<th>Mobile</th>
<th>Photo</th>
<th>Source</th>
<th class="no-sort"> Action</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(window).load(function () {
var $ = jQuery;
var oAllLinksTable = $("#demo_account_listing").dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": baseurl + 'accounts/get_account_listing',
"sPaginationType": "bootstrap",
"oLanguage": {
"sEmptyTable": "No account found.",
"sProcessing": "<img src='<?php echo base_url(); ?>/assets/global/img/loading-spinner-blue.gif'>"
},
"columnDefs": [{
"targets": 'no-sort',
"orderable": false
}],
"aoColumnDefs": [{"bVisible": true, "aTargets": [0]}],
"order": [[0, "desc"]],
processing: true,
"fnServerParams": function (aoData) {
var last_days = $('input[name=days_filter]:checked').val();
aoData.push({name: "days_filter", value: last_days});
},
"fnRowCallback": function (nRow, aData, iDisplayIndex) {
var oSettings = oAllLinksTable.fnSettings();
$("td:nth-child(2)", nRow).html(oSettings._iDisplayStart + iDisplayIndex + 1);
$(nRow).attr("id", 'tr_' + aData[0]);
$("td:nth-child(1)", nRow).html("
<input type='checkbox' name='contacts[]' class='mail-checkbox check_' value='" + aData[0] + "'>");
return nRow;
}
});
var action_radio = '<div class="pull-right check_filter" id="filter_group_radio"><span>
<input type="radio" name="days_filter" id="dsv" class="form-control days_filter" value="7"> 
Last7 Days</span>&nbsp;<span>
<input type="radio" id="df" name="days_filter" class="form-control days_filter" value="14">
Last 14 Days &nbsp;</span><span>
<input type="radio" id="dthi" name="days_filter" class="form-control days_filter" value="30">
Last 30 Days&nbsp;</span><span>
<input type="radio" id="dsx" name="days_filter" class="form-control days_filter" value="60">
Last 60 Days</span></div>';
var extra_action = action_radio + '<div class="pull-right">
<a href="<?php echo base_url(); ?>accounts/new_account">
<button class="btn purple-plum pull-right" type="button">Open New Demo Account</button>
</a>&nbsp;</div>';
$custome_search_filter = extra_action + ' <span class="btn blue" style="height:34px;">
<input type="checkbox" class="checkallbox" id="select_all_"></span><div class="pull-right">
<div class="btn-group myremove"><button data-toggle="dropdown" 
class="btn blue dropdown-toggle dropup" aria-expanded="false">
Bulk Action<i class="fa fa-angle-down"></i></button><ul role="menu" 
class="dropdown-menu pull-right">
<li role="presentation"><a data-toggle="modal" class="deleteRecord" 
href="" tabindex="-1" role="menuitem">
Delete</a></li><li role="presentation">
<a data-toggle="modal" class="exportExcel" href="" tabindex="-1"
role="menuitem">Export to excel</a></li></ul></div></div>';
$($custome_search_filter).appendTo("#demo_account_listing_length > label");
$("#demo_account_listing_length").parent().removeClass('col-md-6').addClass('col-md-10');
$("#demo_account_listing_filter").parent().removeClass('col-md-6').removeClass('col-sm-12');
$(function () {
$(document).on('change', '.days_filter', function (event) {
event.preventDefault();
oAllLinksTable.fnFilter(this.value, 12);
$(this).find('#filter_group_radio input:radio').prop('checked', true);
});
});
$(document).on('click', '.checkallbox', function () {
if ($('#select_all_').is(':checked')) {
$(".check_").prop("checked", "checked");
} else {
$(".check_").removeAttr('checked');
}
});
$(document).on('click', '.check_', function () {
var $this = $(this);
// $this will contain a reference to the checkbox
var numberOfChecked = $('.check_:checked').length;
var totalCheckboxes = $('.check_').length;
var numberNotChecked = totalCheckboxes - numberOfChecked;
if (numberOfChecked == totalCheckboxes) {
$('#select_all_').prop('checked', 'checked');
}
else {
$('#select_all_').removeAttr('checked');
}
});
$(document).on('click', '.deleteRecord', function (e) {
e.preventDefault();
var allVals = [];
$('.check_').each(function () {
if ($(this).is(':checked')) {
allVals.push($(this).val());
}
});
if ($('.check_').is(':checked')) {
bootbox.confirm("Are you sure you want to delete?", function (result) {
if (result == true) {
$.ajax({
url: baseurl + 'accounts/removeAccounts?time=' + timestamp,
type: 'post',
data: 'atype=la&rids=' + allVals,
dataType: 'json',
success: function (response) {
$("#showmessage_jscbf").html("");
switch (response.Mstatus) {
case 'success':
$.each(response.idds.split(','), function () {
$("#tr_" + this).hide();
});
$(".trigger_reload").trigger('click');
break;
case 'error':
$("#showmessage_jscbf").html(response.msg);
break;
}
}
});
}
});
return false;
} else {
alert("Please select one record to delete.")
}
});
$(document).on('click', '.exportExcel', function (e) {
e.preventDefault();
var allVals = [];
$('.check_').each(function () {
if ($(this).is(':checked')) {
allVals.push($(this).val());
}
});
if ($('.check_').is(':checked')) {
$("#aidds").val(allVals);
document.Gexcel.submit();
} else {
alert("Please select one records to export.")
}
});
});
$(function () {
$(document).on('click', '.removeRcords', function (event) {
event.preventDefault();
var idss = $(this).attr('id');
var rid = idss.split("_")[1];
do_remove_ajax('account_type_remove', rid);
});
});
</script>
Notes:
I. Gexcel is a form where all selected ids will be store in hidden id aidds textbox.
II. demo_account_listing_length , you can just open your firebug and can get your id from there.you can see in above html that my id is demo_account_listing so datatable attaching his event to this id.
III. action_radio , $custome_search_filter , extra_action is the filter html , we have to inject to datatables.
IV. fnRowCallback function is a datatable function , i have to put s.no there also $("td:nth-child(1)", nRow) is checkbox which will inject with primary key of your table in mysql.
V. bootbox.confirm is alert box , you can replace simple confim alert box of javascript if you don't need.
VI. $.each(response.idds.split(','), function () { $("#tr_" + this).hide();}); from ajax response comma seperated ids will be revert back from your controller.
3. Your controller function will go like below
public function get_account_listing() {
$this->load->model('common');
$aColumns = array('id', 'id', 'account_no', 'regdate', 'daysleft', 'name', 'email', 
'country', 'mobile', 'leverage', 'balance', 'lead_source');
$aColumnsWhere = array('a.id', 'a.account_no', 'a.date_time', 'a.email', 'a.leverage', 'a.balance',
'da.firstname', 'da.lastname', 'da.regdate', 'da.mobile', 'c.country_name', 'da.lead_source');
$sIndexColumn = "id";
$sTable = "account";
//custome filter
$days_filter = (int) $this->input->get('days_filter', TRUE);
$iDisplayStart = $this->input->get('iDisplayStart', true);
$iDisplayLength = $this->input->get('iDisplayLength', true);
$iSortCol_0 = $this->input->get('iSortCol_0', true);
$iSortingCols = $this->input->get('iSortingCols', true);
$sLimit = "";
if (isset($iDisplayStart) && $iDisplayLength != '-1') {
$sLimit = "LIMIT " . $iDisplayStart . ", " .
$iDisplayLength;
}
if (isset($iSortCol_0)) {
$sOrder = "ORDER BY ";
for ($i = 0; $i < intval($iSortingCols); $i++) {
if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
$sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . "
" . trim($_GET['sSortDir_' . $i]) . ", ";
}
}
$sOrder = substr_replace($sOrder, "", -2);
if ($sOrder == "ORDER BY") {
$sOrder = "";
}
}
$sSearch = $this->input->get('sSearch', true);
$sWhere = "";
if ($sSearch != "") {
$sWhere = "AND (";
for ($i = 0; $i < count($aColumnsWhere); $i++) {
$sWhere .= $aColumnsWhere[$i] . " LIKE '%" . $sSearch . "%' OR ";
}
$sWhere = substr_replace($sWhere, "", -3);
$sWhere .= ')';
}
if ($days_filter != '') {
$sWhere .= "AND (";
$sWhere .= '' . $aColumnsWhere[2] . ' BETWEEN DATE_SUB(NOW(),INTERVAL ' . $days_filter . ' DAY) AND 
NOW()';
//$sWhere .= 'DATE('.$aColumnsWhere[12].')' . " BETWEEN 
'" . DATE('Y-m-d',strtotime($start_date)) . "' AND '".DATE('Y-m-d',strtotime($end_date))."'";
$sWhere .= ')';
}
/* Individual column filtering */
for ($i = 0; $i < count($aColumns); $i++) {
if ($_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {
if ($sWhere == "") {
$sWhere = " WHERE ";
} else {
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i] . " LIKE '%" . trim($_GET['sSearch_' . $i]) . "%'";
}
}
$sEcho = $this->input->get('sEcho');
$result = $this->common->demo_account_listing($sTable, $sWhere, $sOrder, $sLimit, 
$aColumns, $sIndexColumn, $sEcho);
echo json_encode($result);
}
4. Your model code goes like below
function demo_account_listing($sTable, $sWhere, $sOrder,$sLimit, $aColumns, $sIndexColumn, $sEcho){
$sJoin_q_fields = "SELECT SQL_CALC_FOUND_ROWS a.id,a.account_no,a.date_time,
a.email,a.leverage,a.balance, da.regdate, da.firstname as name,
da.mobile, c.country_name as country, da.lead_source";
$sJoin_q = " FROM (account a)";
$sJoin_q .= ' INNER JOIN demo_register da ON a.email = da.email';
$sJoin_q .= ' INNER JOIN country c ON da.country = c.id';
$sJoin_q .= ' WHERE a.act_type = "ABC" ';
$qJoin = $sJoin_q_fields . $sJoin_q . ' ' . $sWhere . ' ' . $sOrder . ' ' . $sLimit;
$rResult = $this->db->query($qJoin);
$rResult_array = $rResult->result_array();
$iFilteredTotal = count($rResult_array);
/* Total data set length */
$sJoin_q_count = "SELECT COUNT(" . $sIndexColumn . ") AS TotalRecords";
$sQuery_TR = $sJoin_q_count . $sJoin_q.$sWhere;
$rResult_TR = $this->db->query($sQuery_TR);
$rResult_array_TR = $rResult_TR->result_array();
$iTotal = $rResult_array_TR[0]['TotalRecords'];
$output = array(
"sEcho" => intval($sEcho),
"iTotalRecords" => intval($iTotal),
"iTotalDisplayRecords" => intval($iTotal), //$iFilteredTotal,
"aaData" => array()
);
$i = 0;
$last = intval($iTotal);
$seclast = intval($iTotal) - 1;
foreach ($rResult_array as $aRow) {
$row = array();
foreach ($aColumns as $col) {
if ($col == 'daysleft') {
$rem = $this->ref_time - strtotime($aRow['regdate']);
$row[] = 30 - floor($rem / 86400);
} else if ($aRow[$col] == 'D') {
$row[] = '<a href="javascript:void(0)" id="E_' . $aRow['id'] . '" name=""
class="btn btn-success btn-sm "><i class="entypo-check"></i> Enable</a>';
} else if ($aRow[$col] == 'E') {
$row[] = '<a href="javascript:void(0)" id="D_' . $aRow['id'] . '"
name="broker_account_status_request_ed" class="btn btn-danger btn-sm ">
<i class="entypo-minus"></i> Disable</a>';
} else {
$row[] = $aRow[$col];
}
}
$i++;
if ($i == $last || $i == $seclast) {
$classaction = 'dropup';
} else {
$classaction = '';
}
array_push($row, '<div class="btn-group ' . $classaction . ' ">
<button data-toggle="dropdown" class="btn red dropdown-toggle" aria-expanded="false">Action
<i class="fa fa-angle-down"></i>
</button>
<ul role="menu" class="dropdown-menu pull-right">
<li role="presentation">
<a href="' . base_url() . 'accounts/change_mt4_pw/' . $aRow['id'] . '" tabindex="-1" role="menuitem">
Change Password
</a>
</li>
<li role="presentation">
<a href="' . base_url() . 'accounts/delete_account/' . $aRow['id'] . '" tabindex="-1" role="menuitem">
Delete Account
</a>
</li>
<li role="presentation">
<a href="' . base_url() . 'accounts/link_account/' . $aRow['id'] . '" tabindex="-1" role="menuitem">
Link Account
</a>
</li>
</ul>
</div>');
$output['aaData'][] = $row;
}
return $output;
}
5. Your view load function will goes like below
public function index() {
$data['meta_title'] = 'Accounts';
$data['meta_keywords'] = 'Accounts';
$data['meta_desc'] = 'Accounts';
$data['top_mobile_menu'] = 'admin/dashboard/top_mobile_menu';
$data['top_menu'] = 'admin/dashboard/top_menu';
$data['main'] = 'admin/dashboard/accounts/account_listing';
$data['footer'] = 'admin/dashboard/footer';
$this->load->vars($data);
$this->load->view($this->admin_dashboard);
}
6. Your function for exporting i am using dompdf library for codeigniter. you can get it after googling.
public function create_document() {
$this->load->helper('dompdf');
$this->load->helper('file');
$this->load->model('prints');
$account_ids = $this->input->post('aidds');
$account_type = $this->input->post('atype');
$result = $this->prints->print_account_listing(format_in_clause($account_ids));
if (!empty($result)) {
$this->load->library('excel');
$this->excel->to_excel($result, "Aaccount-Listing");
exit;
} else {
$this->session->set_flashdata('msg',
alertmessage($message_type = 'alert-danger', $message = 'Unable to process your requiest.'));
redirect(base_url() . 'accounts');
}
}
7. Your function for removing records.
public function removeAccounts() {
$this->load->model('common');
$id = trim($this->input->post('rids'));
$account_type = trim($this->input->post('atype'));
if (isset($id)) {
$thread_ids = explode(",", $id);
foreach ($thread_ids as $values) {
$this->common->do_remove_records('account', array('id' => $values, 'act_type' => 'DEMO'));
}
echo json_encode(array('Mstatus' => 'success', 'idds' => $id,
'msg' => alertmessage($message_type = 'alert-success', $message = 'Accounts has been removed.')));
} else {
echo json_encode(array('Mstatus' => 'error',
'msg' => alertmessage($message_type = 'alert-danger', $message = 'Error in process. Try later.')));
}
}
8. alertmessage is a helper function for generating bootstrap message.
function alertmessage($message_type, $message) {
$output = '';
if (!empty($message_type) && !empty($message)) {
$output.="<div class='alert showmessage_jscbf " . $message_type . "'>" . $message . "</div>";
return $output;
} else {
return $output;
}
}
9. format_in_clause is a helper function.
function format_in_clause($string) {
if (isset($string)) {
$realArray = explode(',', $string);
if (is_array($realArray)) {
$stringForIn = "'" . implode("','", $realArray) . "'";
return $stringForIn;
} else {
return $string;
}
} else {
return NULL;
}
}

Tuesday 10 November 2015

Neteller payment integration core Php , Curl.

You may also see the post here https://yourlearn.in/posts/view/6/neteller-payment-integration-core-php and know and read much more about it.


If you want to implement Neteller payment using Core / Simple Php below is code for you can get it. I have used below code for only testing purpose so i can check weather Neteller working OR not. Please never used below code on production if you want to use below code in production you have to modify it accordingly like.
 
You can create function for CURL request , passing merchant info in hidden field is not good way you can take that in your PHP SCRIPT.
 
To set up a Business Test Account, you need to provide the below information to merchantsupport@paysafe.com and they`ll set it up for you
Merchant descriptor name: Your descriptor name
Contact Person: Your Name
Phone number: Your Number
Country:      Your Country          
Contact E-mail: create an email on gmail , yahoo...etc and put here.
Currency Accounts: Your Currency USD..etc
 
You can find Member Test Accounts in the Integration Manual on page 153.
 
You can go to https://merchant.neteller.com/merchflux/public/index and grab your merchant info and replace in hidden field. You have to request there customer support for enabling API client key and secret key for testing purpose. During my code testing i found invalid client issue response from API so for issue i have to add IP address there. Another issue i have faced minimum amount , Amount should be passed as $_POST['amount']*100.
 
1. Your All Php , Html Code file or you can say your view file will goes like below.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>NETELLER</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>NETELLER</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form method="post" action=""><br>
Version: <input type="text" name="version" value="4.1"><br>
Amount : <input type="text" name="amount" value="1"><br>
Currency: <input type="text" name="currency" value="USD"><br>
net_account: <input type="text" name="net_account" value="12 digit number"><br>
secure_id: <input type="text" name="secure_id" value="326415"><br>
<div><hr></div>
MI: <input type="hidden" name="merchant_id" value="08762"><br>
MK: <input type="hidden" name="merch_key" value="client_id:client_key"><br>
MTID: <input type="hidden" name="merch_transid" value="<?php echo time(); ?>"><br>
MN: <input type="hidden" name="merch_name" value="Company Ltd"><br>
MA: <input type="hidden" name="merch_account" value="Comany Ltd"><br>
<input type="submit" name="button" value="Make transfer">
</form>
</body>
</html>
<?php
if (isset($_POST['button'])) {
$fields = array(
'version' => $_POST['version'],
'amount' => urlencode($_POST['amount']),
'currency' => $_POST['currency'],
'net_account' => urlencode($_POST['net_account']),
'secure_id' => urlencode($_POST['secure_id']),
'merchant_id' => urlencode($_POST['merchant_id']),
'merch_key' => urlencode($_POST['merch_key']),
'merch_transid' => urlencode($_POST['merch_transid']),
'button' => 'Make Transfer'
);

$merchantkey = $_POST['merch_key'];
$amount_value = $_POST['amount']*100;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "https://api.neteller.com/v1/oauth2/token?grant_type=client_credentials");
curl_setopt($ch, CURLOPT_USERPWD, $merchantkey);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json", "Cache-Control:no-cache"));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$serverOutput = curl_exec($ch);
$serverOutput = json_decode($serverOutput);
if (isset($serverOutput->error) && $serverOutput->error != '') {
header("Location:your_page.php?status=" . $serverOutput->error->message . "&payment_type=neteller");
exit;
}
if (isset($serverOutput->accessToken) && $serverOutput->accessToken != "") {
$access_token = $serverOutput->accessToken;
$requestParams = array(
"paymentMethod" => array(
"type" => "neteller",
"value" => $_SESSION["email"],
),
"transaction" => array (
"merchantRefId" => (string) time(),
"amount" => $amount_value,
"currency" => "USD"
),
"verificationCode" => $_POST['secure_id']
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_URL, "https://api.neteller.com/v1/transferIn");
curl_setopt($curl, CURLOPT_HTTPHEADER, 
array("Content-Type:application/json", "Authorization: Bearer $access_token"));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($requestParams));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$serverOutput = curl_exec($curl);
$serverOutput = json_decode($serverOutput);
if (isset($serverOutput->error->code) && $serverOutput->error->message != '') {
header("Location:payment.php?status=" . urlencode($serverOutput->error->message) . "
&payment_type=neteller");
exit;
}
curl_close($ch);
//Success full return array;
echo "<pre>";
print_r($serverOutput);
}
}
?>

Saturday 30 May 2015

Datatables ajax bootstrap pagination with codeigniter

If you want to implement datatables with ajax using codeigniter and you can also use code if you are using core php stuff in your application.

1. You need to include required jQuery for datatables , ajax processing.
<script src="<?php echo base_url(); ?>assets/js/jquery-1.11.0.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery.dataTables.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/dataTables.bootstrap.js"></script>
<script src="<?php echo base_url(); ?>assets/js/datatables/responsive/js/datatables.responsive.js">
</script>
<script src="<?php echo base_url(); ?>assets/js/datatables/jquery.dataTables.columnFilter.js">
</script>
        
2. Your html source file or you can say your view file will goes like below.
<div class="main-content">
<div class="row"><h2>Brokers Listing</h2>
<div class="panel panel-primary" data-collapsed="0">
<div class="panel-body">
<table class="table table-bordered table-striped datatable" id="broker_listing">
<thead><tr>
<th class="no-sort">#</th>
<th>Broker Name</th>
<th>Email</th>
<th>Created Date</th>
<th>Status</th>
<th class="no-sort">Actions</th>
</tr></thead><tbody></tbody>
</table>
</div>
</div>
        
<script type="text/javascript">
jQuery(window).load(function(){
var $ = jQuery;
$("#broker_listing").dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": baseurl+'broker/get_broker_listing',
"sPaginationType": "bootstrap",
"columnDefs": [ {
"targets": 'no-sort',
"orderable": false,
}],
"fnRowCallback": function(nRow, aData, iDisplayIndex) {
nRow.setAttribute('id',"tr_"+aData[0]);
}
});
});
$(function() {
$(document).on('click', '.removeRcords', function(event) {
event.preventDefault();
var idss=$(this).attr('id');
var rid=idss.split("_")[1];
do_remove_ajax('broker_remove',rid);
});
});
</script>
        
3. Your controller function will go like below
public function get_broker_listing() {
$this->load->model('common');
$aColumns = array('broker_id' ,'name', 'email', 'created_date', 'status');
$sIndexColumn = "broker_id";
$sTable = "cbf_broker_registration";
$iDisplayStart=$this->input->get('iDisplayStart',true);
$iDisplayLength=$this->input->get('iDisplayLength',true);
$iSortCol_0=$this->input->get('iSortCol_0',true);
$iSortingCols=$this->input->get('iSortingCols',true);
$sLimit = "";
if ( isset($iDisplayStart) && $iDisplayLength != '-1' )
{
$sLimit = "LIMIT ". $iDisplayStart.", ".$iDisplayLength;
}
if ( isset($iSortCol_0))
{
$sOrder = "ORDER BY ";
for($i=0 ; $i<intval( $iSortingCols ) ; $i++ ){
if($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
{
$sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if( $sOrder == "ORDER BY" ){
$sOrder = "";
}
}
$sSearch=$this->input->get('sSearch',true);
$sWhere = "";
if ( $sSearch != "" ){
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ ){
$sWhere .= $aColumns[$i]." LIKE '%".$sSearch."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
/* Individual column filtering */
for($i=0 ; $i<count($aColumns) ; $i++){
if($_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != ''){
if($sWhere == ""){
$sWhere = "WHERE ";
}else{
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%'";
}
}
$sEcho=$_GET['sEcho'];
$result=$this->common->broker_listing($sTable, $sWhere, $sOrder, $sLimit, $aColumns,$sIndexColumn,
$sEcho);
echo json_encode($result);
}
        
4. Your model function will goes like below. you can also give edit and remove functionality for that just returning Edit Link and class " removeRcords ". you can put other links as your requirement.
function broker_listing($sTable, $sWhere, $sOrder, $sLimit, $aColumns,$sIndexColumn,$sEcho) {
$sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM $sTable $sWhere $sOrder $sLimit";
$rResult = $this->db->query($sQuery);
$rResult_array=$rResult->result_array();
$iFilteredTotal = count($rResult_array);
/* Total data set length */
$sQuery_TR = "SELECT COUNT(".$sIndexColumn.") AS TotalRecords FROM $sTable";
$rResult_TR = $this->db->query($sQuery_TR);
$rResult_array_TR=$rResult_TR->result_array();
$iTotal = $rResult_array_TR[0]['TotalRecords'];
$output = array("sEcho" => intval($sEcho),"iTotalRecords" => intval($iTotal),
"iTotalDisplayRecords" => intval($iTotal), //$iFilteredTotal,
"aaData" => array()
);
foreach($rResult_array as $aRow){
$row = array();
foreach($aColumns as $col){
if($aRow[$col]=='D'){
$row[] = 'Disable';
}else{
$row[] = $aRow[$col];
}
}
array_push($row, '<a href="'.base_url().'admin/broker/edit_broker/'.$aRow['broker_id'].'" 
class="editRcords btn btn-default btn-sm btn-icon icon-left"><i class="entypo-pencil"></i> 
Edit</a> <a href="javascript:void(0)" id="brkr_'.$aRow['broker_id'].'" 
class="removeRcords btn btn-danger btn-sm btn-icon icon-left">
<i class="entypo-cancel"></i> Remove</a>');
$output['aaData'][] = $row;
}
return $output;
}
        
5. You can setup jQuery function through out your project OR Application. you have to pass two param action_key and id for removing records.
function do_remove_ajax(action_key,id){
$.ajax({
url baseurl+'controller/do_remove',
type 'POST',
data{idid,action_keyaction_key},
dataType 'json',
beforeSend function() {
},
complete function() {
},
success function(response) {
switch (response.Mstatus) {
case 'success'
$("#"+response.process_id).hide();
break;
case 'error'
showalert(response.msg,'showmessage_jscbf');
break;
default
break;
}
}
});
}
        
6. Your view load function will goes like below
public function view_broker() {
$data['meta_title'] = 'Broker Listing';
$data['meta_keywords'] = 'Broker Listing';
$data['meta_desc'] = 'Broker Listing';
$data['sidebarmenu'] = 'sidebar_menu';
$data['top_menu'] = 'top_menu';
$data['main'] = 'broker_listing';
$data['footer'] = 'footer';
$this->load->vars($data);
$this->load->view($this->admin_dashboard);
}
        
NOTE: Flow goes like below sidebar menu link click--->view_broker() function call---> call ajax function get_broker_listing() ---> call model function broker_listing--->controller return json formate required for datatables.

Thursday 14 May 2015

Creating store procedure Mysql Insert

Showing you some examples of creating store procedure in mysql.
1. "At The Rate" sign used for local variable declare.
2. For calling a store procedure use function below. i am using Codeigniter.
 public function AddBooking(){
  $sql="call usp_AddBooking()";
 $parameters=array();
 $query = $this->db->query($sql,$parameters);
 return $query->result();
 }
 DROP PROCEDURE IF EXISTS `usp_AddBooking` $$
 CREATE PROCEDURE `usp_AddBooking`(
 IN iVendorId INT,
 IN iCustomerId INT, 
 IN iServiceId INT,
 IN dServiceBookingTime DATETIME,
 IN dArrivalTime DATETIME
 )
BEGIN
 DECLARE iBookingId INT default 0;
 BEGIN
 -- ERROR
 set ErrorCode = -999;
 rollback;
 END;
 DECLARE exit handler for sqlwarning
 BEGIN
 -- WARNING
 set ErrorCode = -888;
 rollback;
 END;
 START TRANSACTION;
 INSERT INTO skin_booking 
 (iVendorId 
 ,iCustomerId 
 ,iServiceId
 ,dServiceBookingTime 
 ,dArrivalTime
  ,eStatus
 ,dCreatedDate 
 ,iBookingId 
 ) 
 VALUES 
 (iVendorId 
 ,iCustomerId 
 ,iServiceId 
 ,dServiceBookingTime 
 ,dArrivalTime
 ,'1'
 ,NOW()
 ,iBookingId 
 );
 SET @iBookingId = LAST_INSERT_ID();
 SELECT @iBookingId as BookingId;
 COMMIT;
 END$$

Register users and login through store procedure mysql

1. Signup a user through store procedure.
2. "mysecret" here you can use your key. password will be encrypted using AES
3. You can call store procedure like below
CALL`AddCustomerDetails`('David Warnor','david@gmail.com','12','male','2377.34','34343.343');
CREATE PROCEDURE `AddCustomerDetails`(
 IN `vCustomerName` VARCHAR(50),
 IN `vEmail` VARCHAR(50),
 IN `vPassword` VARCHAR(50),
 IN `eGender` VARCHAR(10),
 IN `dLatitude` FLOAT,
 IN `dLongitude` FLOAT
)
BEGIN
 DECLARE ResultCount INT default 0;
 DECLARE skey VARCHAR(15) default 'mysecret';
 DECLARE eStatus INT default 1;
 DECLARE iCustomerId INT;

 SET @ResultCount = (SELECT COUNT(iCustomerId) FROM table_name WHERE vEmail = vEmail);
 IF (@ResultCount > 0) THEN
 SET @iCustomerId = 0;
 SELECT @iCustomerId;
 ELSE
 INSERT INTO table_name
 (vCustomerName
 ,vEmail
 ,vPassword
 ,eGender
 ,dLatitude
 ,dLongitude
 ,eStatus
 ,dCreatedDate
 )
 VALUES
 (vCustomerName
 ,vEmail
 ,AES_ENCRYPT(vPassword,skey)
 ,eGender
 ,dLatitude
 ,dLongitude
 ,eStatus
 ,NOW()
 );
 SET @iCustomerId = LAST_INSERT_ID();
 SELECT @iCustomerId as CustomerId;
 END IF;
END
1. Now above will add a entry to your mysql table let create a store procedure which will validate and check credentials.
ALL `CheckLogin`('david@gmail.com', '123123', '0');
CREATE PROCEDURE `CheckLogin`(
 IN `Email` VARCHAR(255),
 IN `Psw` VARCHAR(255),
 IN `UserType` INT(11)
)
BEGIN
 DECLARE ResultCount INT;
 DECLARE ResultMessage varchar(15);
 DECLARE skey VARCHAR(15) default 'secrets';
 IF (UserType = 0) THEN
 SET @ResultCount = (SELECT COUNT(C.iCustomerId) FROM customerdetails C 
 WHERE C.vEmail = Email AND C.vPassword = AES_ENCRYPT(Psw,skey) AND C.eStatus = 1);
  IF (@ResultCount > 0) THEN #For Customer
  SELECT * from customerdetails C WHERE C.vEmail = Email AND C.vPassword = AES_ENCRYPT(Psw,skey) 
  AND C.eStatus = 1;
  ELSE
 SET @ResultMessage='User not found.';
  SELECT @ResultMessage;
  END IF;
 ELSE
 SET @ResultCount = (SELECT COUNT(V.iVendorId) FROM vendor V WHERE V.vEmail = Email 
 AND V.vPassword = AES_ENCRYPT(Psw,skey) AND V.eStatus = 1);
 IF (@ResultCount > 0) THEN
  SELECT * from vendor V WHERE V.vEmail = Email AND V.vPassword = AES_ENCRYPT(Psw,skey) 
  AND V.eStatus = 1;
 ELSE
 SET @ResultMessage='vendor not found.';
  SELECT @ResultMessage;
 END IF;
 END IF;
END

Monday 11 May 2015

Ajax captcha using codeigniter php bootstrapvalidator

I will show you how you can create a captcha validation with Codeiginter based on Ajax.
1. Below is my model name as Mcaptcha
class Mcaptcha extends CI_Model {
protected $ci;
function __construct() {
// Call the Model constructor
parent::__construct();
$this->ci =& get_instance();
}
function setCaptcha(){
$this->load->helper('captcha');
$rand = substr(md5(microtime()),rand(0,26),5);
$vals = array(
'img_path' => FCPATH.'assets/captcha/',
'img_url' => base_url().'assets/captcha/',
'expiration' => 1800,// half hour
'font_path' => FCPATH.'assets/fonts/Cabin-BoldItalic.ttf',
'img_width' => '140',
'img_height' => 30,
'word' => $rand,
);
$cap = create_captcha($vals);
$this->ci->session->set_userdata(array('cpt'=>$rand, 'img' => $cap['time'].'.jpg'));
return $cap['image'] ;
}
}
    
2. Your controller function will goes like below
public function send_us_email() {
$this->load->library('form_validation');
$this->load->model('mcaptcha');
$this->form_validation->set_error_delimiters('<span>', '</span>');
$this->form_validation->set_rules('sname', 'Name', 'trim|required|max_length[20]|xss_clean');
$this->form_validation->set_rules('captcha', 'Captcha', 'trim|required|max_length[5]|
callback_validate_captcha|xss_clean');
if ($this->form_validation->run() == FALSE){
// if any fields on form not validated properly we need to unset session and unlink captcha
image previously created and then regenerate captcha and passing it to Cmessage.
if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
$this->session->unset_userdata('cpt');
$this->session->unset_userdata('img');
$captcha = $this->mcaptcha->setCaptcha();
echo json_encode(array('Mstatus'=>'error','Cmessage'=>$captcha,'msg' => validation_errors()));
}else{
$sname=set_value('sname');
$captcha=set_value('captcha');
$data=array('name'=>$sname);
$send_us_a_email_template= $this->load->view('email_templates/send_us_a_email', $data, true);
$this->email->from('youremail@domain.com',"YourTITLE");
$this->email->to($semail);
$this->email->subject('Customer Query Request');
$this->email->message($send_us_a_email_template);
if ($this->email->send()){
// same logic above if every thing goes well.
if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
$this->session->unset_userdata('cpt');
$this->session->unset_userdata('img');
echo json_encode(array('Mstatus'=>'success','Cmessage'=>'We have recieved 
your email and we will get back to you shortly. Thanks.','msg'=>''));
}else{
echo json_encode(array('Mstatus'=>'error','Cmessage'=>'','msg' => 'Error 
in processing your query. Please try later.'));
}
}
}
    
3. Below is call back function to validate captcha enter by user.
public function validate_captcha($str){
if($str != $this->session->userdata['cpt']){
$this->form_validation->set_message('validate_captcha', 'Wrong captcha code, 
hmm are you the Terminator?');
return false;
}else{
return true;
}
}
    
4. Your jQuery goes like below
$(document).ready(function() {
$('#submit-link-form').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
linkname: {
validators: {
notEmpty: {
message: 'The name is required.'
},
stringLength: {
min: 4,
message: 'Name must be 4 characters long.'
}
}
},
scaptcha: {
validators: {
notEmpty: {
message: 'Captcha verification is required.'
}
}
}
}
})
.on('success.form.bv', function(e) {
e.preventDefault();
var $form = $(e.target);
var bv = $form.data('bootstrapValidator');
$.ajax({
url: $form.attr('action')+'?time='+timestamp,
type: $form.attr('method'),
data: $form.serialize(),
dataType:'json',
beforeSend: function() {
},
complete: function() {
},
success: function(response){
switch(response.Mstatus){
case 'success':
break;
case 'error':
break;
default:
break;
}
}
});
});
});
    
5. Your bootstrap model popup will looks like below
<div class="container">
<div class="modal fade animate1 faster-modal" id="send-us-email-modal" tabindex="-1" role="dialog" 
aria-labelledby="sendusemailLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span>
<span class="sr-only">Close</span></button>
<h4 class="modal-title" id="sendusemailLabel">Send Us Email</h4>
</div>
<div class="modal-body">
<?php echo form_open(base_url().'root/send_us_email',array('id' =>'send-us-email-form',
'name' =>'send-us-email-form','method'=>'post'));?>
<div class="faster-ajax-loader faster_ajax_loader" style="display:none;"></div>
<aside class="form-group">
<div class="popup_message"></div>
</aside>
<aside class="form-group">
<input type="text" class="form-control required" placeholder="Your Name" name="sname" id="sname" />
</aside>
<aside class="form-group form-capcha"> <span class="generated-capcha"><img 
src="<?php echo base_url();?>images/default.jpg" width="140" height="30" alt="Verification Code">
</span><a href="javascript:void(0);" title="Refresh Verification Code">
<span class="glyphicon glyphicon-refresh refresh-regenerate"></span></a> </aside>
<aside class="form-group">
<input class="form-control text required" id="captcha" type="text" name="captcha" value="" 
placeholder="Verification Code" />
</aside>
<aside class="form-group">
<input type="submit" class="btn-features animate1" value="Send Us Email" />
</aside>
</form>
</div>
</div>
</div>
</div>
</div>
    
6. If you would like to refresh captcha if it is not visible properly to users then refresh captcha on Link / Image click .Your js code will goes like below
$(function(){
$(document).on('click', '.refresh-regenerate', function(){
var myformclick=$(this).closest('form').attr('id');
$.ajax({
url: baseurl+"root/generate_captcha",
type: "POST",
data: "cap=1",
cache: false,
dataType:'json',
beforeSend: function() {
$("#"+myformclick).find(".faster_ajax_loader").css('display','block');
},
complete: function() {
$("#"+myformclick).find(".faster_ajax_loader").css('display','none');
},
success: function(response){
$("#"+myformclick).find(".generated-capcha").html(response.Cmessage);
}
});
});
});
    
7. I am calling generate_captcha function so that on each click new captcha image will be generated.
public function generate_captcha(){
if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
$this->load->model('mcaptcha');
$this->session->unset_userdata('cpt');
$this->session->unset_userdata('img');
$captcha = $this->mcaptcha->setCaptcha();
echo json_encode(array('Mstatus'=>'success','Cmessage'=>$captcha,'msg' => validation_errors()));
}
    

Creating subdomain on amazon ubuntu Ec2

1. Create a directory from command line
sudo touch /var/www/your-directory
2. Create a conf file on location /etc/apache2/site-available/
 i. sudo touch /etc/apache2/site-available/your-directory-name.domainname.com.conf
 ii. Just copy 000-default.config data to newly created file above
 sudo cp /etc/apache2/site-available/000-default.conf 
/etc/apache2/site-available/your-directory-name.domainname.com.conf
 iii. open file for edit 
 sudo nano /etc/apache2/site-available/your-directory-name.domainname.com.conf
 and replace 

 DocumentRoot /var/www/your-directory-name

 iv. sudo service apache2 reload.
 v. sudo service apache2 restart. 
3. After above process go to amazon hosted zone just follow below steps
 1. create a records set put name of your choice in name required fields
 2. put www.yourdomain.com. in value and save records set. 

Minify your javascript files offline with uglifyjs

You can compress or minify your Javascript / jQuery code by visiting to resources which is available but if you want to use it on your localhost so you can use it and run like below on windows.
1. Installed Node.js
2. Set envirnment variable
NODE_PATH
C:\Program Files\nodejs\UglifyJS\bin\uglify;C:\Program Files\nodejs\node.exe;
3. Download uglify master from gits and put in folder
C:\Program Files\nodejs\uglifyjs
4. run command
Run npm -g install uglify-js
final if you want to minify js
5. Run uglifyjs -o app.min.js app.js
Note: app.min.js is your name and app.js is your source js which you want to compress OR minify.

Tomcat 8.0.21 running in ubuntu 14.04 TLS

I am explaining every step to run tomcat in ubuntu 8.0.21 and how to setup your projects and running Servlets ,Jsp.
1. Install JDK 7 before installing tomcat.
sudo apt-get install openjdk-7-jdk
2. Download the latest version of tomcat tomcat.apache.org , i downloaded Apache Tomcat 8.0.21
I rename dowonload folder to "apache-tomcat"
and move it to location /usr/local/apache-tomcat
go to /usr/local/apache-tomcat/conf/tomcat-users.xml
or you can edit from terminal sudo nano /usr/local/apache-tomcat/conf/tomcat-users.xml
place below lines & save. [ctrl+^+x then press Y]
<role rolename="manager-gui">
<role rolename="admin-gui">
<user password="rohit" roles="manager-gui,admin-gui" username="rohit">
</user>
</role>
</role>
3. We have to create a bash file for running and stoping tomcat. Create a new file tomcat8021 in /etc/init.d/ and add the below code
 #!/bin/bash
export CATALINA_HOME=/usr/local/apache-tomcat
PATH=/sbin:/bin:/usr/sbin:/usr/bin
start() {
sh $CATALINA_HOME/bin/startup.sh
}
stop() {
sh $CATALINA_HOME/bin/shutdown.sh
}
case $1 in
start|stop) $1;;
restart) stop; start;;
*) echo "Run as $0 "; exit 1;;
esac
4. Give 755 permission
    sudo chmod 755 /etc/init.d/tomcat8021
5. For starting stoping tomcat
   sudo /etc/init.d/tomcat8021 start / stop
6. We need to set Classpath and java home varibale to work properly. so i edited the file call environment place below lines there.
sudo nano /etc/environment
CLASSPATH=.:/usr/lib/jvm/default-java/bin:/usr/local/apache-tomcat/lib/servlet-api.jar
JAVA_HOME=/usr/lib/jvm/default-java

Creating a new project in ubuntu 14.04 TLS

1. I created a folder called store in /usr/local/apache-tomcat/
2. store(Project Folder) ---> WEB-INF ---> classes(DIR) , lib(DIR) , web.xml (file)
3. web.xml file looks like below
<web-app>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
4. Inside classes folder your source file HelloWorld.java will be store for compiling it use below command
mangel@mangel-desktop:/usr/local/apache-tomcat/webapps/store/WEB-INF/classes$ 
javac -classpath /usr/local/apache-tomcat/lib/servlet-api.jar HelloWorld.java
5. After compile .class file created by above command , then you need to create a context file ,
Go to cd /usr/local/apache-tomcat/conf/Catalina/localhost/ from terminal.
sudo nano store.xml (store is the name of your project folder).
Just paste below line
<!-- Store Context -->
<context debug="0" docbase="store" path="/store" reloadable="true">
</context>
So above all configure manually. just open locahost:8080/store/HelloWord.

Creating subdomain on Digital Ocean

Directory
html refers to main site.
demo , blog outside html (folder) refers to subdomain.
1. Create a directory from command line
 sudo touch /var/www/your-directory
2. Create a conf file on location /etc/apache2/site-available/
 sudo touch /etc/apache2/sites-available/your-directory-name.domainname.com.conf
 Just copy 000-default.config data to newly created file above by below command
 sudo cp /etc/apache2/sites-available/000-default.conf 
 /etc/apache2/site-available/your-directory-name.domainname.com.conf
 open file for edit 
 sudo nano /etc/apache2/sites-available/your-directory-name.domainname.com.conf
 and replace 
 DocumentRoot /var/www/your-directory-name
 sudo service apache2 reload.
 sudo service apache2 restart. 
3. After above proceee go to amazon hosted zone just follow below steps.
 Create a records set put name of your choice in name required fields
 Put www.yourdomain.com. in value and save records set. it will take 10-15 min to process by amazon.