Monday, June 10, 2019

Success or Error Message Display in Codeigniter

I use this for flash data and it's easy to use. first, need to you have create session and then in your controllers' method use this just before where you want to redirect your page.
On Controller after creating a session and don't forget to load session and url library.
$this->session->set_flashdata('success', 'Oops. This email id already exist.');
redirect("Your method or page");
In this case, you no need to add any extra php code in your particular view page.Just copy and paste this below script in your footer.php.Good luck and hope it will help for your problem.
<!-- Code for flashdata toaster -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
<script type="text/javascript">
    <?php if($this->session->flashdata('success')){ ?>
        toastr.success("<?php echo $this->session->flashdata('success'); ?>");
    <?php }else if($this->session->flashdata('error')){  ?>
        toastr.error("<?php echo $this->session->flashdata('error'); ?>");
    <?php }else if($this->session->flashdata('warning')){  ?>
        toastr.warning("<?php echo $this->session->flashdata('warning'); ?>");
    <?php }else if($this->session->flashdata('info')){  ?>
        toastr.info("<?php echo $this->session->flashdata('info'); ?>");
    <?php } ?>
</script>
<!-- End of flashdata script -->

Thursday, April 4, 2019

How to run laravel github project on localhost. Full step by step

1. Download the laravel project from github or any source. 2. Copy that project in hotdocs folder and open the folder location in cmd. 3. Now first rename the "env.example file to.env" 4. You can configure the database information here. 5. Now open cmd and run some commands... -Run composer install or php composer.phar install -Run php artisan key:generate -Run php artisan migrate -Run php artisan db:seed to run seeders, if any. -Run php artisan serve that's all.. Problems discussion:: you may have the problem with the composer or the php... check all are installed.. and the paths are added as the environment variable... These two paths have to be added to run laravel project... 1. C:\ProgramData\ComposerSetup\bin 2. C:\xampp\php

Youtube video link: https://www.youtube.com/watch?v=ngzOHoyITfM

Thursday, March 21, 2019

MySQL Aggregate Functions

1). MySQL COUNT function returns the number of records in a select query and allows you to count all rows in a table or rows that match a particular condition.

Ex: SELECT COUNT(*) AS "Total Rows" FROM employees;

2).The IN operator allows you to specify multiple values in a WHERE clause.

Ex: SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, ...);

3).The MySQL SUM function returns the summed value of an expression.

Ex: SELECT SUM(column_name) FROM table_name WHERE condition;

4).The MySQL MIN function returns the minimum value in a set of values.

Ex: SELECT MIN(column_name) FROM table_name WHERE condition;

5).The MySQL MAX function returns the maximum value in a set of values.

Ex: SELECT MAX(column_name) FROM table_name WHERE condition;

6).The MySQL HAVING clause is used in the SELECT statement to specify filter conditions for a group of rows or aggregates.
Ex: Now suppose based on the above table you want to count the number of customers in each country. Only include countries with more than 1 customers, then you can do it as follows:

SELECT COUNT(CustomerID) AS "Number of customers", Country FROM customers GROUP BY Country HAVING COUNT(CustomerID) > 1;

7).The MYSQL GROUP BY Clause is used to collect data from multiple records and group the result by one or more column.
The GROUP BY statement is often used with aggregate functions such as SUM, AVG, MAX, MIN and COUNT. It is generally used in a SELECT statement.

Ex: SELECT COUNT(CustomerID) AS "Number of customers", Country FROM customers GROUP BY Country;

8).The MySQL BETWEEN operator selects values within a given range in a SELECT, INSERT, UPDATE, and DELETE statement. The values can be numbers, text, or dates.

Ex: SELECT * FROM books WHERE Price BETWEEN 10 AND 25;

9).MySQL DISTINCT with multiple columns:
When querying data from a table, you may get duplicate rows. In order to remove these duplicate rows, you use the DISTINCT clause in the SELECT statement.

Ex: SELECT DISTINCT state, city FROM customers WHERE state IS NOT NULL ORDER BY state, city;

MySQL query to find the second highest salary

Second maximum salary using sub query and IN clause:


SELECT MAX(salary) FROM employees WHERE salary NOT IN ( SELECT Max(salary) FROM employees);

Second maximum salary using sub query and < operator instead of IN clause:


SELECT MAX(salary) From employees WHERE salary < ( SELECT Max(salary) FROM employees);

Second maximum salary using the LIMIT clause in query:


SELECT salary FROM (SELECT salary FROM employees ORDER BY salary DESC LIMIT 2) AS Emp ORDER BY salary LIMIT 1;

Monday, January 21, 2019

Generate Access Token and Call the function with access token and send multiple records at single shot and get multiple validation and success responses:

Generate Access Token and Call the function with access token and send multiple records at single shot and get multiple validation and success responses:

In Controller:

<?php
require APPPATH . '/libraries/REST_Controller.php';
class Monthlydata extends REST_Controller {
    public function __construct() {
                parent::__construct();
                date_default_timezone_set('Asia/Kolkata');
                $this->load->model('Monthlydata_model');
    }
    public function generate_access_token_post(){
      $username = $this->post('username');
      $password = $this->post('password');
      $data =array('username'=>$username,'password'=>$password);
      $accesResponse= $this->Monthlydata_model->createAccessToken($data);
      $this->set_response($accesResponse, REST_Controller::HTTP_OK);
    }
    public function monthly_update_post(){
    $lrecord = array();
    $inputdata = array();
    $access_token = $this->post('access_token');
    $user_id = $this->post('user_id');
    $ibb_dealer_code = $this->post('ibb_dealer_code');
  if(!empty($access_token) && !empty($user_id)){
    $checkAccessToken = $this->Monthlydata_model->check_access_token($access_token,$user_id);
    if(is_array($checkAccessToken) && count($checkAccessToken)>0){
    $inputdata = $this->post('inputData');
    $successData= array();
    $err_msgs = array();
      $i=0;
      $row_count = 0;
      $fail_count = 0;
      $abm_fail_count = 0;
      $int_validation_count = 0;     
foreach ($inputdata as $val) {
            $ibb_dealer_code = trim($val['ibb_dealer_code']);
            $do_issued_as_on_date = trim($val['do_issued_as_on_date']);
            if(empty($ibb_dealer_code) || empty($do_issued_as_on_date)){
                   $fail_count++;
              }             
              if (filter_var($do_issued_as_on_date, FILTER_VALIDATE_INT)) {
          $checkIbbDealerCode = $this->Monthlydata_model->ibb_dealer_code_already_exists($ibb_dealer_code);
             if(!empty($ibb_dealer_code) && $checkIbbDealerCode[0]['abm_remarks']!='') {             
              $lrecord['percentage_achievement']=0;
              if($checkIbbDealerCode[0]['target_for_the_curr_month']!=0 && $checkIbbDealerCode[0]['target_for_the_curr_month'] >0){
                    $lrecord['percentage_achievement'] = round(($do_issued_as_on_date/$checkIbbDealerCode[0]['target_for_the_curr_month'])*100);

                   $lrecord['difference_in_units'] = round($do_issued_as_on_date-$checkIbbDealerCode[0]['target_for_the_curr_month']);
              }
              $lrecord['do_issued_as_on_date'] = $do_issued_as_on_date;
              $lrecord['last_modified_on'] = date('Y-m-d H:i:s');
              $lrecord['last_modified_by'] = $val['user_id'];
              $this->Monthlydata_model->update_single_row($checkIbbDealerCode[0]['ibb_dealer_code'],$lrecord);             
              $successData[$i]['message'] = "Updated successfully";
              $successData[$i]['id'] = $checkIbbDealerCode[0]['id'];
              $successData[$i]['ibb_dealer_code'] = $checkIbbDealerCode[0]['ibb_dealer_code'];
              $i++; 
              $row_count++;   
           
            }else{
            $abm_fail_count++;         
            }
        }elseif(!empty($do_issued_as_on_date)){
         $int_validation_count++;

        } // do_issued_as_on_date integer validation end
       
      } // foreach end
      if($fail_count>0){
        array_push($err_msgs,$fail_count." rows are failed to update, IBB dealer code and Do issued as on date fields are mandatory");
      }
      if($abm_fail_count>0){
        array_push($err_msgs,$abm_fail_count." rows are failed to update, ABM does not have entered certain details or IBB dealer code was not found");
      }
      if($int_validation_count>0){
        array_push($err_msgs,$int_validation_count." rows are failed to update, do issued as on date should be an integer");
      }
      $this->set_response(['errors'=>$err_msgs,'success' =>$successData,'status'=>'success','status_code'=>'200'], REST_Controller::HTTP_OK);
     }else{
      $this->set_response(['status'=>'false','message'=>'Access token expired or invalid'], REST_Controller::HTTP_OK);
    }
  }else{
        $this->set_response(['status'=>'false','message'=>'access token or user id cannot be empty'], REST_Controller::HTTP_OK);
  }
}
}


In Model:

<?php
class Monthlydata_model extends CI_Model {
    function check_access_token($access_token,$user_id){
        $this->db->select('id,access_token,expires_at');
          $this->db->from('user_login');
          $this->db->where('access_token',$access_token);
          $this->db->where('expires_at >=',date("Y-m-d H:i:s"));
          //$this->db->where('id',$user_id);
          return $this->db->get()->result_array();
          //echo $this->db->last_query();die;       
    }
    function createAccessToken($data){
          $this->db->select('id,access_token,expires_at');
          $this->db->from('user_login');
          $this->db->where('username',$data['username']);
          $this->db->where('password', md5($data['password']));
          $query = $this->db->get();
          if($query->num_rows() == 1)
          {
           $result = $query->row();
           if($result->expires_at < date("Y-m-d H:i:s")){
            $accessToken = $this->randomKey(39);
            $expire_time = date("Y-m-d H:i:s", strtotime('+24 hours'));
           
            $this->db->where('id',$result->id);
            $this->db->update('user_login',array('access_token'=>$accessToken,'expires_at'=>$expire_time));
            $return = array('status'=>'success','access_token'=>$accessToken,'expires_at'=>$expire_time);   
           } else {
            $return = array('status'=>'success','access_token'=>$result->access_token,'expires_at'=>$result->expires_at);
           }
          } else {
           $return = array('status'=>'failure','message'=>'Invalid username/password.');
          }
        return $return;
    }
     function randomKey($length){
      $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));
      $key = null;
      for($i=0; $i < $length; $i++) {
        $key .= $pool[mt_rand(0, count($pool) - 1)];
      }
      return $key;
     }
    function ibb_dealer_code_already_exists($ibb_dealer_code){
        $this->db->where('ibb_dealer_code',$ibb_dealer_code);
        $query = $this->db->get('master_data_reports');
        if ($query->num_rows() > 0){
          return $data = $query->result_array();
        }else{
          return false;
        }
    }
    function update_single_row($lead_id,$data) {
        $this->db->where("ibb_dealer_code", $lead_id);
        $this->db->update('master_data_reports', $data);
        return true;
    }

}

?>

Tuesday, January 8, 2019

Post values file handling

 // POST VALUES
  date_default_timezone_set('Asia/Kolkata');
  $path = 'debug_log/debug_log.txt';
  file_put_contents($path, print_r('<<<<< POST VALUES_'.date('Y-m-d H:i:s'),true).' >>>>>', FILE_APPEND);
  $this->content = str_repeat(PHP_EOL, 1);
  $this->content .= print_r($_POST,true);
  $this->content .= str_repeat(PHP_EOL, 1);
  $this->content .= '============================================' . PHP_EOL . PHP_EOL; 
  file_put_contents($path, $this->content, FILE_APPEND); 
 // FILES VALUES
  file_put_contents($path, print_r('<<<<< IMAGES_'.date('Y-m-d H:i:s'),true).' >>>>>', FILE_APPEND);
  $this->content_file = str_repeat(PHP_EOL, 1);
  $this->content_file .= print_r($_FILES,true);
  $this->content_file .= str_repeat(PHP_EOL, 1);
  $this->content_file .= '============================================' . PHP_EOL . PHP_EOL;
  file_put_contents($path, print_r($this->content_file,true), FILE_APPEND);

  echo '<pre>'; print_r($_POST);
  echo '<pre>'; print_r($_FILES);
  exit;

Date wise Ascending or Descending Order (AND) Order by multiple different columns

Current month lead first then previous months leads and then "follow_up_date_time" null leads:

SELECT `lead_id`, `lead_cre_type`, `lead_cre_date`, `lead_status`, `agmt_no`, `cus_name`, `cus_mobile`, `state`, `ms`.`city_name`, `agmt_no`, `veh_reg_no`, `mfcw_id`, `branch`, `branch_code`, `mmv`, `given_for`, `cc_remark`, `remarks`, `reason`, `assigned_on`, `final_agmt_no`, `follow_up_date_time`, `inprgs_datetime`, `lead_date_time`, `application_no` as `emlap_id`, `mf_lead_id` as `crm_id`, `final_agmt_no` as `contract_number`, `contract_date`, `sub_stage`, `appl_no`, `lead_from`
FROM `custom_leads`
LEFT JOIN `master_cities` as `ms` ON `ms`.`city_id` = `custom_leads`.`city_id`
WHERE `assigned_to` = '4900'
AND `lead_status` = '3'
AND (`follow_up_date_time` IS NULL OR  date_format(substr(follow_up_date_time,1,10),'%Y-%m-%d') <= '2019-01-31' OR   month(date_format(substr(follow_up_date_time,1,10),'%Y-%m-%d')) <= month(CURRENT_DATE())) ORDER BY
date_format(substr(follow_up_date_time,1,10),'%Y-%m-%d')  >= CURRENT_DATE() DESC,
date_format(substr(follow_up_date_time,1,10),'%Y-%m-%d')  ASC,
date_format(substr(follow_up_date_time,1,10),'%Y-%m-%d')  < CURRENT_DATE() DESC

Order by multiple different columns(Set of leads one after another with descending order by date):


SELECT
  `ui`.`uid`,
    `ui`.`user_fname` AS `exec_name`,
    `l`.`mf_lead_id`,
    `ul`.`sap_code`,
    `ui`.`user_mobile` AS `exec_mobile`,
    `l`.`lead_id`,
    DATE_FORMAT(SUBSTR(l.lead_cre_date, 1, 10),
            '%d/%m/%Y') AS lead_cre_date,
    `l`.`lead_cre_type`,
    DATE_FORMAT(SUBSTR(l.last_modified_on, 1, 10),
            '%d/%m/%Y') AS last_modified_on,
     l.lead_category,     
    `l`.`lead_status`,
    `l`.`abm_lead_status`,
    `l`.`cus_name`,
    `l`.`cus_mobile`,
    `l`.`veh_reg_no`,
    `l`.`mfcw_id`,
    `l`.`agmt_no`,
    `l`.`final_agmt_no`,
    `l`.`branch`,
    `l`.`branch_id`,
    `l`.`mmv`,
    `l`.`given_for`,
    `l`.`assigned_to`,
    `l`.`cc_remark`,
    `l`.`remarks`,
    DATE_FORMAT(SUBSTR(l.do_date, 1, 10), '%d/%m/%Y') AS do_date,
    `l`.`abm_cnc_remarks`,
    DATE_FORMAT(SUBSTR(l.follow_up_date_time, 1, 10),
            '%d/%m/%Y') AS follow_up_date_time,
    DATE_FORMAT(SUBSTR(l.inprgs_datetime, 1, 10),
            '%d/%m/%Y') AS inprgs_datetime,
    `C`.`city_name`,
    `l`.`lead_for`,
    `l`.`mmfsl_stage`,
    `l`.`mmfsl_code`,
    `l`.`appl_no`,
    `l`.`final_agmt_no`,
    `l`.`veh_fin_amt`,
    `l`.`emlap_user_id`,
    `l`.`emlap_date_time`,
    (CASE
        WHEN l.lead_from = 'referral-app' THEN T.state_name
        ELSE S.state_name
    END) AS state_name,
    `l`.`application_no`,
    DATE_FORMAT(SUBSTR(l.first_contacted_date, 1, 10),
            '%d/%m/%Y') AS first_contacted_date,
    (CASE
        WHEN A.user_type = '1' THEN 'Super Admin'
        WHEN A.user_type = '3' THEN 'Executive'
        WHEN A.user_type = '5' THEN 'ABM'
        WHEN A.user_type = '16' THEN 'Mini User'
    END) AS user_type,
    `A`.`username` AS `lead_created_username`,
    `l`.`lead_type`,
    (CASE
        WHEN l.workable_month = '1' THEN 'Workable This Month'
        WHEN l.workable_month = '2' THEN 'Workable Next Month'
    END) AS workable_month
FROM
`custom_leads` AS `l`
LEFT JOIN
`user_login` AS `ul` ON `ul`.`id` = `l`.`assigned_to`
LEFT JOIN
`user_login` AS `A` ON `A`.`id` = `l`.`lead_cre_user_id`
LEFT JOIN
`user_info` AS `ui` ON `ui`.`uid` = `ul`.`id`
LEFT JOIN
`master_cities` AS `C` ON `C`.`city_id` = `l`.`city_id`
LEFT JOIN
`master_states` AS `S` ON `S`.`state_id` = `l`.`state_id`
LEFT JOIN
`refertowin_master_states` AS `T` ON `T`.`id` = `l`.`state_id`
WHERE
`l`.`lead_status` != '8'
ORDER BY
   (CASE
      WHEN lead_category = 'CLMS' AND lead_cre_type='Bulk' THEN 0
      WHEN lead_category IS NULL AND lead_cre_type='Bulk' THEN 1
       WHEN lead_from = 'referral-app' AND lead_cre_type='Single' THEN 2
       WHEN lead_from IS NULL AND lead_cre_type='Single' THEN 3
       ELSE 4   
    END),
   date(lead_cre_date) desc