Showing posts with label Codeigniter. Show all posts
Showing posts with label Codeigniter. Show all posts

Thursday, 29 September 2022

Model query function in codeigniter

 (A) Model query :-

1. Find One Row With Primary key

$data['directory'] = $model->where('is_active',1)->find(1); 

2. Find One Row with where

 $data['result'] = $modelOU->where('username', $email)->first();

3. Find Multipal Row 

$data['reletedProduct'] = $modelP->where('is_active ','1')->findAll(4);

4. Find Multipal Row with Random

$data['result'] = $modelP->where('is_active ','1')->orderBy('rand()')->findAll();

$data['result'] = $modelP->where('is_active ','1')->orderBy('id','RANDOM')->findAll();

5. Find Multipal Row with Random

$data['reletedProduct'] = $modelP->where('is_active ','1')->orderBy('rand()')->findAll(4);


 

 

 

(B) Builder query :-

 $db      = \Config\Database::connect();

 $builder = $db->table('tablename');  

2. Find Multipal Row 

$query = $builder->where('is_active', 1)->select('id, name')->limit(5)->get();

3. Find Multipal Row With like

$query = $builder->like('name', $this->request->getVar('term'))->select('id, name')->limit(5)->get();

 

date validation codeigniter 4

validation function in codeigniter 4

    required
    valid_date
    matches[field_name]
    min_length[x]
    max_length[x]
    exact_length[x]
    alpha
    alpha_numeric
    alpha_dash
    numeric
    integer
    is_natural
    is_unique
    is_not_unique
    is_natural_no_zero
    valid_email
    valid_emails
    valid_ip
    valid_base64
    is_unique[table.email]
    edit_unique[users.user_name.'.$id.']'

Error Message customized

 

 'category_id' => ['label' => 'Category', 'rules' => 'required'],  
https://codeigniter4.github.io/CodeIgniter4/libraries/validation.html#form-validation-tutorial 



Monday, 25 May 2020

Session set use unset in codeigniter


Create :
$this->session->set_userdata('regCheck', $LastInsertId); // value set


Use :
$this->session->userdata('regCheck');




Unset :

$this->session->unset_userdata('regCheck');

Last Insert id codeigniter



Model : 

$sql=$this->db->query("INSERT INTO `enquiry` (`code`,`name`,`email`,`phone`,`country`,`description`,`created_dt`)
VALUES (
'".$this->db->escape_str($this->input->post('code'))."',
'".$this->db->escape_str($this->input->post('name'))."',
'".$this->db->escape_str($this->input->post('email'))."',
'".$this->db->escape_str($this->input->post('phone'))."',
'".$this->db->escape_str($this->input->post('country'))."',
'".$this->db->escape_str($this->input->post('description'))."',
            Now()
)");

        $insert_id = $this->db->insert_id();
        return  $insert_id;

Monday, 23 March 2020

url routing in codeigniter

Url Routing in Codeigniter : 


$title = "Here's a string!";
$url_title = url_title($title);


$route['default_controller'] = 'web';

$route['logout']='web/logout';

$route['videos'] = 'web/videos';

$route['videos'] = 'web/videos';

$route['news'] = 'Web/newsAll/';

$route['news-list/(:num)'] = 'Web/news/9'; // news List 

$route['news/(:any)/(:num)'] = 'web/newsDetail/$1/$2';  // new detail 

$route['(:any)/(:num)'] = 'web/page/$1/$2';  //page


Tuesday, 3 March 2020

random step data in codeigniter

Random step data in codeigniter

View : 

<?php 
if($c%10==0){
if(!empty($AdsRandomStep)){ 
$total_array = count($AdsRandomStep);
$random_keys=rand(0,$total_array-1); 
echo '<div class="col-sm-12"><img src="'.base_url('upload/advertisement/').$AdsRandomStep[$random_keys]->path.'" class="adsStep" width="100%" /></div>';


 }} $c++; } } ?>

Thursday, 13 February 2020

Form tag in codeigniter

<?php echo form_open('administration/Home/addSettingCode',array("id"=>"myform","class"=>"form-horizontal form-label-left","enctype"=>"multipart/form-data"));?>
 <input type="hidden" name="id" value="<?php echo (isset($settingData->id) && $settingData->id!=''?$settingData->id:'')?>">
 <input type="hidden" name="old_path" value="<?php echo (isset($settingData->logo) && $settingData->logo!=''?$settingData->logo:'')?>">



<div class="col-md-12">
                                                <div class="position-relative form-group">
                                                  <label for="examplePassword" class=""><span class="text-danger">*</span> About Us </label>
 <script src="//cdn.ckeditor.com/4.4.7/full/ckeditor.js"></script>
                                                                  <textarea rows="5" name="s8" id="s8" class="form-control" placeholder="Enter About Us" required><?php echo (isset($settingData->s8) && $settingData->s8!=''?$settingData->s8:'')?></textarea>
                                             <script>
                                                CKEDITOR.replace('s8', {
                                                  // Define the toolbar groups as it is a more accessible solution.
                                                  toolbarGroups: [{
                                                      "name": "basicstyles",
                                                      "groups": ["basicstyles"]
                                                    },
                                                    {
                                                      "name": "links",
                                                      "groups": ["links"]
                                                    },
                                                    {
                                                      "name": "paragraph",
                                                      "groups": ["list", "blocks"]
                                                    },
                                                    {
                                                      "name": "styles",
                                                      "groups": ["styles"]
                                                    }
                                                 
                                                  ],
                                                  // Remove the redundant buttons from toolbar groups defined above.
                                                  removeButtons: 'Underline,Strike,Subscript,Superscript,Anchor,Styles,Specialchar'
                                                });
                                              </script>

                                                </div>
                                            </div>



  <?php echo form_close();?>

Tuesday, 11 February 2020

Export Mysql Data to CSV File in Codeigniter

Controllers :

public function exportCSV(){
     
        $myData = $this->Home_model->getexportCSV();

        // file name
        $filename = 'User_Data'.date('Ymd').'.csv';
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$filename");
        header("Content-Type: application/csv; ");

        // file creation
        $file = fopen('php://output', 'w');

        $header = array("Mobile","Name");
        fputcsv($file, $header);

        foreach ($myData as $line){
            fputcsv($file,array($line->mobile,$line->name));
        }

        fclose($file);
        exit;
    }




Model :


public function getexportCSV(){
$sql=$this->db->query(" SELECT * FROM  `user`   ");
return $sql->result();

}

Saturday, 8 February 2020

sms api set in codeigniter

CONSTANTS.PHP

/* custom development */
define('SMS_URL','http://sms.xxxxxxx.in/submitsms.jsp?');
define('SMS_USER','xxxxxxxxx');
define('SMS_KEY','xxxxxxx');
define('SMS_SENDER_ID','xxxxxxx');
define('SMS_SUPPORT_NO','1234567891');

/* custom development */


controller 

if($insertCheck=='1'){
$this->session->set_flashdata('msg', '<p class="alert alert-success">Your request has been sent successfully.</p>');

/* sms */
$mobile = SMS_SUPPORT_NO;
$message = "New Suggestion/Problem Received\n
Name : ".$this->input->post('name')."
Mobile : ".$this->input->post('mobile')."
Ward No :  ".$this->input->post('ward')."
\n\n:: Apna Roopangarh ::";
$this->Home_model->SendUnicodeSms($mobile,$message);

$mobile_user = $this->input->post('mobile');
$message_user = "आपकी शिकायत / सुझाव हमें प्राप्त हो गए हैं
\nजल्द ही हम आपसे संपर्क करेंगे
\nग्राम पंचायत रुपनगढ़";
$this->Home_model->SendUnicodeSms($mobile_user,$message_user);
/* sms */

}

Models

public function SendSms($mobiles,$message){

 
$key=SMS_KEY;  //   
$user=SMS_USER;    //
$senderid = SMS_SENDER_ID;

/*  sms */
$ch = curl_init();                    // initiate curl
$url = SMS_URL; // where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);  // tell curl you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$user&key=$key&mobile=$mobiles&message=$message&senderid=$senderid&accusage=1"); // NTFSMS , INFOSM, ROZGAR,define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the output in string format
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
//curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Accept-Language: hi;q=0.5"));
$output = curl_exec ($ch); // execute
//echo $status = curl_getinfo($ch);
//print_r($output);
curl_close ($ch); // close curl handle
//var_dump($output); // show output
/*   sms  */


             
}


public function SendUnicodeSms($mobiles,$message){

 
$key=SMS_KEY;  //   
$user=SMS_USER;    //
$senderid = SMS_SENDER_ID;


$ch = curl_init();  // initiate curl
$url = SMS_URL; // where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);  // tell curl you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$user&key=$key&mobile=$mobiles&message=$message&senderid=$senderid&accusage=1&unicode=1"); // NTFSMS , INFOSM, ROZGAR,define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the output in string format
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
//curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Accept-Language: hi;q=0.5"));
$output = curl_exec ($ch); // execute
//echo $status = curl_getinfo($ch);
//print_r($output);
curl_close ($ch); // close curl handle
//var_dump($output); // show output



             
}

Sunday, 2 February 2020

Email Format Codeigniter


public function addContactCode(){

$from_email = "sunilkalla2011@gmail.com";  // jaha se email send hoga
        $to_email = $this->input->post('email');  // jisko email jana h
       
        $subject = "Alakhpurajharod : Enquiry";

$message = "<h1>Alakhpurajharod : Enquiry</h1>";
$message .= "<b>Name : ".$this->input->post('name')."</b><br/>";
$message .= "<b>Phone: ".$this->input->post('mobile')."</b><br/>";
$message .= "<b>Description : </b><br/>";
$message .= "".$this->input->post('message')."";

$header = "From:".$this->input->post('email')." \r\n";
$header1 = "MIME-Version: 1.0\r\n";
$header2 = "Content-type: text/html\r\n";

        //Load email library
        $this->load->library('email');
        $this->email->from($from_email, 'Identification');
        $this->email->to($to_email);
        $this->email->cc('sunilkalla2011@gmail.com');  // copy email id
        $this->email->cc('in.mukeshsaini@gmail.com');  // copy email id

        $this->email->subject($subject);
        $this->email->message($message);
     

        $this->email->set_header('MIME-Version', '1.0; charset=utf-8');
        $this->email->set_header('Content-type', 'text/html');


        //Send mail
        if($this->email->send()){
            $this->session->set_flashdata("email_sent","<p class='flashmessage'>Email Sent Successfully.</p>");
        }
        else{
            $this->session->set_flashdata("email_sent","<p class='flashmessage'>You have encountered an error</p>");
        }

redirect("home/index/#mail");
     

}



2 ----------------------------------------------------------------

if($data['result']) {
                $_SESSION['CartItem'] = '';
                $this->load->library('email');
                $fromemail="digicardindia2020@gmail.com";
                $toemail = $_POST['email'].",in.mukeshsaini@gmail.com,digicardindia2020@gmail.com";
                $subject = "Digi Card India : ".$_POST['bussiness'];
                $mesg = $this->load->view('front/order_confirm',$data,true);
                $_SESSION['CartItem'] = $mesg;
                $config=array(
                'charset'=>'utf-8',
                'mailtype' => 'html'
                );
                $this->email->initialize($config);
                $this->email->to($toemail);
                $this->email->from($fromemail, "Order Confirmation");
                $this->email->subject($subject);
                $this->email->message($mesg);
                $mail = $this->email->send();
                if($mail) {
                    $this->session->set_flashdata('msg', '<p class="alert alert-success">Thanks for your order.</p>');
                } else {
                   // echo 'not send';exit();
                }
           }

Monday, 20 January 2020

delete in codeigniter

public function deleteNewsCategory($id){

$sql=$this->db->query("DELETE FROM `news_category` WHERE  id='".(int)$id."'");

return $sql;

}

update in codeigniter

public function updateNewsCategory($id,$image){

$sql=$this->db->query("UPDATE `news_category` SET

`name`='".$this->db->escape_str($this->input->post('name'))."',
`mobile`='".$this->db->escape_str($this->input->post('mobile'))."',
`detail`='".$this->db->escape_str($this->input->post('detail'))."',
    `created_dt`=Now(),
`isactive`='".$this->db->escape_str($this->input->post('isactive'))."'
WHERE id='".(int)$id."'");


return $sql;
}

Email send in Codeigniter

$from_email = "domin.help24@gmail.com";
        //$to_email = $this->input->post('email');
        $to_email = 'in.mukeshsaini@gmail.com';

        $subject = "All Free : Product Enquiry";

$message = "<h1>All Free : Enquiry</h1>";
$message .= "<b>Product : ".$this->input->post('code')."</b><br/>";
$message .= "<b>Name : ".$this->input->post('name')."</b><br/>";
$message .= "<b>Email : ".$this->input->post('email')."</b><br/>";
$message .= "<b>Phone: ".$this->input->post('phone')."</b><br/>";
$message .= "<b>Country: ".$this->input->post('country')."</b><br/>";
$message .= "<b>Description : </b><br/>";
$message .= "".$this->input->post('description')."";

$header = "From:".$this->input->post('email')." \r\n";
$header1 = "MIME-Version: 1.0\r\n";
$header2 = "Content-type: text/html\r\n";

        //Load email library
        $this->load->library('email');
        $this->email->from($from_email, 'Identification');
        $this->email->to($to_email);
        $this->email->cc('domin.help24@gmail.com');


        $this->email->subject($subject);
        $this->email->message($message);
       

        $this->email->set_header('MIME-Version', '1.0; charset=utf-8');
        $this->email->set_header('Content-type', 'text/html');


        //Send mail
        if($this->email->send()){
            $this->session->set_flashdata("email_sent","Congragulation Email Send Successfully.");
        }
        else{
            $this->session->set_flashdata("email_sent","You have encountered an error");
        }

data insert incodeigniter

public function savecardform(){



     
$sql=$this->db->query("INSERT INTO `card` (`location`,`category`,`business`, `name`, `mobile`,`mobile1`, `mobilew`,`landline`,`email`, `tagline`, `gstno`, `landmark`,`address`,`village`,`city`,`pincode`,`state`,`businesspet`,`service`,`timetable`,`about`, `created_dt`, `updated_dt`, `isactive`)
VALUES (
'".$this->db->escape_str($this->input->post('location'))."',
'".$this->db->escape_str($this->input->post('category'))."',
'".$this->db->escape_str($this->input->post('business'))."',
'".$this->db->escape_str($this->input->post('name'))."',
'".$this->db->escape_str($this->input->post('mobile'))."',
'".$this->db->escape_str($this->input->post('mobile1'))."',
'".$this->db->escape_str($this->input->post('mobilew'))."',
'".$this->db->escape_str($this->input->post('landline'))."',
'".$this->db->escape_str($this->input->post('email'))."',
'".$this->db->escape_str($this->input->post('tagline'))."',
'".$this->db->escape_str($this->input->post('gstno'))."',
'".$this->db->escape_str($this->input->post('landmark'))."',
'".$this->db->escape_str($this->input->post('address'))."',
'".$this->db->escape_str($this->input->post('village'))."',
'".$this->db->escape_str($this->input->post('city'))."',
'".$this->db->escape_str($this->input->post('pincode'))."',
'".$this->db->escape_str($this->input->post('state'))."',
'".$this->db->escape_str($this->input->post('businesspet'))."',
'".$this->db->escape_str($this->input->post('service'))."',
'".$this->db->escape_str($this->input->post('timetable'))."',
'".$this->db->escape_str($this->input->post('about'))."',
            Now(),
            Now(),
'0'
)");
return $sql;



}

lazy loader in Codeigniter

View : 

<section class="cardlist" id="results">
            <div id="load_data"></div>
            <div id="load_data_message"></div>
</section>


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

    var limit = 4;
    var start = 0;
    var action = 'inactive';

    function lazzy_loader(limit)
    {
      var output = '';
      for(var count=0; count<limit; count++)
      {
        output += '<center> <div class="loading-info"><img src="<?php echo base_url().'assets/front/'?>images/loading.gif" /></div></center>';

      }
      $('#load_data_message').html(output);
    }

    lazzy_loader(limit);

    function load_data(limit, start)
    {

      $.ajax({
        url:"<?php echo base_url(); ?>Web/cardFetch",
        method:"GET",
        data:{limit:limit, start:start},
        cache: false,
        success:function(data)
        {
          if(data == '')
          {
            $('#load_data_message').html('<center><h5 style="color: green;"> No More Card Available </h5></center>');
            action = 'active';
          }
          else
          {
            $('#load_data').append(data);
            $('#load_data_message').html("<center><h4 style='color: red;'> No More Card Available </h4></center>");
            action = 'inactive';
          }
        }
      })
    }

    if(action == 'inactive')
    {
      action = 'active';
      load_data(limit, start);
    }

    $(window).scroll(function(){
      if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
      {
        lazzy_loader(limit);
        action = 'active';
        start = start + limit;
        setTimeout(function(){
          load_data(limit, start);
        }, 1000);
      }
    });

  });
</script>


Controller : 





public function cardlist()
{
if($this->uri->segment('3')!=''){
$this->session->set_userdata('src_category', $this->uri->segment('3'));
}

if($this->input->post('src_text')!=''){
$this->session->set_userdata('src_text', $this->input->post('src_text'));
}else{
$this->session->set_userdata('src_text','');
}


$data=array();
$data['CardList']=$this->Web_model->getCardList();
$data['CategoryName']=$this->Web_model->getCategoryName();
$data['LocationName']=$this->Web_model->getLocationName();
$data['ads_list_top_ads']=$this->Web_model->getadsData('list_top_ads');
$data['ads_list_footer_ads']=$this->Web_model->getadsData('list_footer_ads');
$this->load->view('front/card_list',$data);
}

function cardFetch()
{
$output = '';
$this->load->model('Web_model');
$data = $this->Web_model->fetch_data($this->input->get('limit'), $this->input->get('start'));
if($data->num_rows() > 0)
{
$bg=1;
            $i=1;
foreach($data->result() as $val)
{
if($val->verified=='1'){  $verifiedPhoto = '<img src="'.base_url('assets/front/icon/verified.png').'"  class="verified" />'; }else{ $verifiedPhoto=''; }


                if($val->path1!=''){
                   $ownerPhoto ='<img src="'.base_url('upload/card/').''.$val->path1.'" class="owner" />';
                      }else{
                  $ownerPhoto ='<img src="'.base_url('assets/front/icon/logoshort.jpg').' " class="owner" />';
                 }



$output .= '
<span class="cardlistitem bg'.$bg++.'">
           
    '.$verifiedPhoto.'         
    <a href="'.base_url('web/detail/').''.$val->id.''.$this->uri->segment('3').'">
       
        <table>
            <tr>
                <td width="25%">
                   '.$ownerPhoto.'
                </td>
                <td width="75%">
        <table style="margin: 5px;">
            <tr><th><span class="t1">'.ucwords( $val->business ).'</span> </th></tr>
            <tr><th><span class="t2"><img src="'.base_url('/assets/front/icon/user.png').'" class="sicon" />'.ucwords( $val->name ).'</span> </th></tr>
            <tr><th><span class="t2"><img src="'.base_url('/assets/front/icon/mobile.png').'" class="sicon" />'.$val->mobile.'</span> </th></tr>     
            <tr><th><span class="t2"><img src="'.base_url('/assets/front/icon/s.png').'" class="sicon" style="background-color: #fff; " />'.substr($val->service,0,26).'</span> </th></tr>   
        </table>
            </td>
            </tr>

            <tr><td colspan="2"><span class="t4">'.ucfirst( $val->address ).'</span></td></tr>
        </table>


    </a>
</span>';



}
}
echo $output;
}




Models : 




function fetch_data($limit, $start)
{

            $src_location = $this->session->userdata('src_location');
            $src_category = $this->session->userdata('src_category');


     
    $src_text = $this->db->escape_str($this->session->userdata('src_text'));

$this->db->select("*");
$this->db->from("card");
if($src_text==''){
    $this->db->where(" category='".$src_category."' && location='".$src_location."' &&  isactive='1' ");              
}else{
      $this->db->where(" category='".$src_category."' && location='".$src_location."' && isactive='1'  && ( business LIKE '%".$src_text."%'  ||  name LIKE '%".$src_text."%' || address LIKE '%".$src_text."%' || mobile LIKE '%".$src_text."%' || service LIKE '%".$src_text."%') ");                      
}

$this->db->order_by("plan", "DESC");
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query;
}





password encode codeigniter


$password=hash("sha256", $this->input->post('pass'));



Form validation in codeigniter


Form Validation ---------------------------------

Type : 

'trim|required|min_length[5]|max_length[12]|valid_email|xss_clean|matches[passconf]|is_unique[table.field]'


$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|matches[passconf]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('email', 'email', 'required|trim|valid_email|xss_clean');

$this->form_validation->set_rules('username', 'User Name', 'required|trim');
$this->form_validation->set_rules('pass', 'Password', 'required|trim');
if ($this->form_validation->run() == FALSE) {

redirect("administration/home");
}else{

}



More Information validation Rules
https://www.tutorialspoint.com/codeigniter/codeigniter_form_validation.htm