Saturday, December 31, 2016

Fetch record order by date, even date column as varchar or text.

function get_followupleads($executive_id) {
    $query = "SELECT le.lead_id,le.bname,le.bcontact,le.sname,le.scontact,le.veh_reg_no,le.case_category,le.follow_up_date_time,rto.city as rto_location
              FROM  `rto_tb_leads` as le
              LEFT JOIN rto_office as rto ON rto.id = le.rto_location
              WHERE follow_up_date_time IS NOT NULL AND lead_cre_user_id = $executive_id
              ORDER BY STR_TO_DATE( follow_up_date_time,  '%d-%m-%Y' )";
              $result = $this->db->query($query);
    $details = $result->result_array();
    //echo $this->db->last_query();     
    if( is_array($details) && count($details) > 0 ) {
            return $details;
         }
         return false;
    }

Monday, December 5, 2016

Firebase Cloud Messaging (FCM) PUSH Notification Documentation (Android)

Example:1

<?php // Dynamic
    date_default_timezone_set("Asia/Kolkata");
    function save_and_send_push_notification(){

        define('FIREBASE_API_KEY', 'AIzaSyDf-uPyTgxcxckH2JLE6lO0XmygxWmjFpS7BU0'); // this api key created from fcm account panel
                $title = trim($this->input->post('title'));
                $message = trim($this->input->post('message'));
                $type = trim($this->input->post('type')); // 'All', 'Multiple'
                $user_ids = trim($this->input->post('user_ids')); // this is an array type


                    $payload = array();
                    $payload['team'] = 'India';
                    $payload['score'] = '5.6';
                    $global = 'global';
                    $to = '/topics/' . $global;
                   
                    $res = array();
                    $res['data']['title']           = $title;
                    $res['data']['is_background']   = false;
                    $res['data']['message']         = $message;
                    $res['data']['image']           = 'http://images.carandbike.com/car-images/big/bmw/1-series/bmw-1-series.jpg';
                    $res['data']['payload']         = $payload;
                    $res['data']['timestamp']       = date('Y-m-d H:i:s');

                if($type == 'All'){
                        $global = 'global'; // Topic name provided by android developer
                        $to = '/topics/' . $global;
                        $fields = array('to'=>$to,'data'=>$res);

                }else{
                          $to = array("ffe3mf5m454","df68dfrbb5","fgfhf9fg9gfg"); // device tokens
                          $fields = array('registration_ids'=>$to,'data'=>$res);

                }

        $url = 'https://fcm.googleapis.com/fcm/send';
        $headers = array(
                        'Authorization: key=' .FIREBASE_API_KEY,
                        'Content-Type: application/json'
                        );
        //Open connection
        $ch = curl_init();
        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_PROXY, '10.166.105.54:3128'); if curl not working in live server add this line
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        //Execute post
        $result = curl_exec($ch);
        if ($result === FALSE)
            die('Curl failed: ' .curl_error($ch));
        //Close connection
        echo $result;
        curl_close($ch);
        // finally if the notification sent. insert these information into one table like=> title,message,image,type and user_ids
}
?>
Example:2
    <?php  Static:
    date_default_timezone_set("Asia/Kolkata");
    // old start
      //define('FIREBASE_API_KEY', 'AIzaSyDf-uPxxcxyTgkH2JccczxLE6lO0XmygxWmjFpS7BU0');
      // $to = 'f7paTxPtMNI:APA91bG5FsRdwdB-W-CmKUDg-5mRgqVEvZ4XEycpel4my0ttR6jEw4ZvtqKD_jROxxcxcz3vkKqV-JPr1ablXjHowY9bQOyAP-sM_kK_zpVdbJuQ-bfO4hG9QyFWjf_193xZuxcxc5IZDtChU6SiF';
   
        // new start
        define('FIREBASE_API_KEY', 'AIzaSyB0J97UiXxcxzcuNNsf9fLRxcHGu4WQ3_Oam3wFgI');
       $to = 'eIE-xNAybZU:APA91bGkrLxceE1mFPfkN9vkBtTuQgmE3LASXAN47HDwCkZfiyFziJ1Ae8GYV8FpRXjsYcT5-vC5AGF0pbxavhIL_j8gxyheKlBqnRxxzcX3CSHD0gvkvfzSH2xcxzcxR8iJDYwGb2ZBVjoeCPLfRs8R';
        $payload = array();
        $payload['team'] = 'India';
        $payload['score'] = '5.6';
            $global = 'global';
      // $to = '/topics/' . $global;
       
        $res = array();
        $res['data']['title']           = 'IBB Trade Offers';
        $res['data']['is_background']   = false;
        $res['data']['message']         = '25 % offers on 1 year used cars';
        $res['data']['image']           = 'http://images.carandbike.com/car-images/big/bmw/1-series/bmw-1-series.jpg';
        $res['data']['payload']         = $payload;
        $res['data']['timestamp']       = date('Y-m-d H:i:s');
                $fields = array(
                        'to'    => $to,
                        'data'  => $res,
                        );

        $url = 'https://fcm.googleapis.com/fcm/send';
        $headers = array(
                        'Authorization: key=' .FIREBASE_API_KEY,
                        'Content-Type: application/json'
                        );
        //Open connection
        $ch = curl_init();
        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_PROXY, '10.166.105.54:3128'); if curl not working in live server add this line
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        //Execute post
        $result = curl_exec($ch);
        if ($result === FALSE)
            die('Curl failed: ' .curl_error($ch));

       //var_dump($result);die;
        //Close connection
        //echo "<pre>"; print_r($fields);
        echo "<pre>"; print_r(json_decode($result));
        echo $result;
        curl_close($ch);
        return $result;
?>

Server Side Validation in Codeigniter and Core PHP

// for server side validation to check all parameters are empty or not, if one parameter value is empty it return false start
        foreach ($this->input->post() as $key => $val){
                $inputArr[$key] = $val;
                unset($inputArr['referid']);
       
        }
    /*foreach ($_POST as $key => $val){ // for core php
                $inputArr[$key] = $val;
        }*/

        foreach($inputArr as $key1 => $value){
            if(empty($value))
            {  
                $response = array( 'status' => 'FALSE', 'message' => 'Some parameters are missing values');
                $this->set_response($response);
                die;
            }
  
        }
        // for server side validation end

**************************** END************************************

**************************** START**********************************
Using jQuery can set the session:
Using Jquery can set the session --> sessionStorage.setItem("rf_possesion",possesion);
get the session name --> sessionStorage.getItem("rf_possesion");
**************************** END************************************

**************************** START**********************************
POSTMAN form submit capture the form post data in controller:
$data = json_decode(file_get_contents("php://input"));

and print the data like this:

echo $data->username;
**************************** END************************************

Monday, July 4, 2016

For Dynamic find_in_set with JOIN Query

    function dynamic_find_in_set($rtoLocations='2,1,1327') {
        $rtoLocations = explode(',', $rtoLocations);
        foreach ($rtoLocations as $row) {
                $listOfIds .= $row.',';
            }
        $rtoLocationStr = rtrim($listOfIds,',');
        $tablename = 'rto_tb_leads';
        $selectedFields = 'lead_id,bname,bcontact,sname,scontact,veh_reg_no,case_category,follow_up_date_time,ofc.rto_office_location as rto_location';
        $matchColumnName = 'rto_tb_leads.rto_location';
        $details = $this->db->query("SELECT $selectedFields from $tablename LEFT JOIN rto_office as ofc ON ofc.id = rto_tb_leads.rto_location where lead_status='2' AND mfcw_exe_status='0' AND FIND_IN_SET($matchColumnName,'".$rtoLocationStr."')")->result_array();
        if( is_array($details) && count($details) > 0 ) {
            return $details;
                 }
            return false;
    }

For Dynamic find_in_set and CREATE INDEX and Full Index Search in MYSQL and event_scheduler

foreach($rechargePlanDetails->result() as $row){
$mainCatIds .= $row->main_cat_id.',';
}
$listOfIds = rtrim($mainCatIds,',');
$tableName = SUB_CATEGORY;
$matchColumnName = 'main_cat_id';
$selectedFields = 'sub_cat_name,value,image';

$extraSubCatDetails = $this->apis_model->dynamic_find_in_set($tableName,$selectedFields,$matchColumnName,$listOfIds);
     
        // for model
        public function dynamic_find_in_set($tableName='',$selectedFields='',$matchColumnName='',$listOfIds=''){
$Query = "select $selectedFields from ".$tableName." where FIND_IN_SET($matchColumnName,'".$listOfIds."')";
$resultVal=$this->ExecuteQuery($Query);
return $resultVal;

}
*************************************************************

Syntax:
CREATE INDEX index_name
ON table_name (column_name, ...);
Ex:
CREATE INDEX HotelName ON activepropertylist (Name, Address1)
***********
How do I check if an index exists on a table field in MySQL?
SHOW INDEX FROM [tablename]

DROP INDEX index_name ON table_name;
*************************************************




For full text index search:


Full Index Search in MYSQL

Introduction to MySQL Full-Text Search:
* MySQL supports text searching by using the LIKE statement and regular expression. However, when the text column is large and the number of rows in a table is increased, using these methods has some limitations.Because of these limitations, MySQL extended a very nice feature so-called full-text search. Technically, MySQL creates an index from the words of the enabled full-text search column and performs searches on this index. MySQL uses a sophisticated algorithm to determine the rows matched against the search query.

Defining FULLTEXT index for existing tables:
* ALTER TABLE  table_name ADD FULLTEXT(column_name1, column_name2,…)
     after that to check whether index is created or not the syntax is " show index from table_name"
   
Removing full-text search columns:
    ALTER TABLE offices DROP INDEX address
 
MySQL Boolean Full-Text Searches:
    SELECT productName, productline FROM products WHERE MATCH(productName) AGAINST('Truck -Pickup' IN BOOLEAN MODE )
 
    totally 3 methods are there among theme i am using MySQL Boolean Full-Text Searches
    1.MySQL Natural Language Search
    2.MySQL Boolean Full-Text Searches
    3.Using MySQL Query Expansion
 
 
    <?php
$HotelName=array();
$Address=array();
$RegionNameLong=array();
$b = str_replace(" "," +",$searchTerm);
/* $resultSet = $this->db->query("select s.RegionNameLong as HotelName, Null as Address from rs_parentregionlist s where MATCH(s.RegionNameLong) AGAINST('+".$b."'IN BOOLEAN MODE) union select a.Name as HotelName, a.Address1 as Address from rs_activepropertylist a where MATCH(a.Name) AGAINST('+".$b."'IN BOOLEAN MODE) OR MATCH(a.Address1) AGAINST('+".$b."'IN BOOLEAN MODE) LIMIT 10");
foreach($resultSet->result() as $row){
$HotelName[] = $row->HotelName;
$Address[] = $row->Address;
}
$datas = array_merge($HotelName,$Address);
$aa= array_unique($datas);
$uniquesValues = array_values($aa);
echo json_encode($uniquesValues);*/

$resultSet1 = $this->db->query("select Name from rs_activepropertylist where MATCH(Name) AGAINST('+".$b."'IN BOOLEAN MODE) LIMIT 50");
$resultSet2 = $this->db->query("select Address1 from rs_activepropertylist where MATCH(Address1) AGAINST('+".$b."'IN BOOLEAN MODE) LIMIT 50");
$resultSet3 = $this->db->query("select RegionNameLong from rs_parentregionlist where MATCH(RegionNameLong) AGAINST('+".$b."'IN BOOLEAN MODE) LIMIT 50");

foreach($resultSet1->result() as $row){
$HotelName[] = $row->Name;
  }
foreach($resultSet2->result() as $row){
$Address[] = $row->Address1;
  }
foreach($resultSet3->result() as $row){
$RegionNameLong[] = $row->RegionNameLong;
  }
$datas = array_merge($HotelName,$Address,$RegionNameLong);
$aa= array_unique($datas);
$data = array_values($aa);
echo json_encode($data);
?>
 
*****************************************************
For event_scheduler:
<?php

include('db.php');
echo mysql_query("SET GLOBAL event_scheduler = ON;");
//echo mysql_query("CREATE EVENT test_event_03 ON SCHEDULE EVERY 10 SECOND STARTS CURRENT_TIMESTAMP DO TRUNCATE trending");
echo mysql_query("CREATE EVENT test_event1 ON SCHEDULE EVERY 1 MONTH STARTS CURRENT_TIMESTAMP DO TRUNCATE trending");
//echo mysql_query("CREATE EVENT test_event_03 ON SCHEDULE EVERY 1 MINUTE STARTS CURRENT_TIMESTAMP ENDS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
//DO INSERT INTO messages(message,created_at)VALUES('Test MySQL recurring Event',NOW());");
echo "Executed";
die;
?>
****************************************