Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 14,049
» Latest member: tt-tom
» Forum threads: 69,687
» Forum posts: 432,615

Full Statistics

Latest Threads
User link - route all req...
Forum: CodeIgniter 4 Support
2 hours ago
» Replies: 4   » Views: 126
Window Modal does not wor...
Forum: Lounge
2 hours ago
» Replies: 14   » Views: 436
Codeigniter is not decodi...
Forum: Issues
8 hours ago
» Replies: 0   » Views: 31
file type crt as mime
Forum: CodeIgniter 3.x
Yesterday, 05:34 PM
» Replies: 2   » Views: 52
Installation Help
Forum: CodeIgniter 4 Support
Yesterday, 03:06 PM
» Replies: 1   » Views: 46
preg_match not working we...
Forum: General Help
Yesterday, 11:59 AM
» Replies: 3   » Views: 81
Search Criteria Ignored, ...
Forum: General Help
Yesterday, 09:38 AM
» Replies: 17   » Views: 347
LightORM
Forum: Addins
Yesterday, 09:34 AM
» Replies: 11   » Views: 1,622
Plugin/Script reccomendat...
Forum: Addins
Yesterday, 06:42 AM
» Replies: 4   » Views: 211
Invisible Recaptcha
Forum: Addins
Yesterday, 03:02 AM
» Replies: 5   » Views: 506

 
  Select Query Error
Posted by: lfmluis - 06-12-2019, 12:51 PM - Forum: General Help - Replies (3)

Hi everyone, i have a problem with a select query, 


Code:
$where = "SELECT FORMAT(SUM(payed), 2) AS payedAmount FROM client_credit WHERE creditStatus = 2 AND idperson = '"
           .$post_data['idperson']. "' AND contractDate
       BETWEEN '"
           . $startDate . "' AND '" . $endDate . "'";
$query = $this->db->query($where);
       if ($query->num_rows() > 0) {
           return $query->result();
       } else {
           return null;
       }

But i get a boolean result, $query = false, and when i execute the same query in mysql console i get the right result, but here i get boolean.

Thank you. Confused


  ALERT: Model soft deletes have changed the underlying data structure
Posted by: kilishan - 06-12-2019, 08:52 AM - Forum: CodeIgniter 4 Development - Replies (1)

A heads up for any developers working on a CI4 codebase. I just merged in a breaking change to the way soft deletes work. Instead of being a simple boolean flag called deleted, the default field has been changed to a new column called deleted_at. This should be either a DATETIME or INTEGER column that matches what that table is using for created_at and updated_at.

This not only brings it in line with the other timestamps across the Model and Entities, but provides a better chance for data forensics on the case something gets deleted so you can help your client figure out what might have caused things to go missing.

I have been thinking about this change for a while now, as I'm not really sure why I originally created it as a boolean. Probably an artifact from examining several MY_Model classes that were popular from previous versions of CI. If that change was ever going to happen, it had to happen prior to a Release Candidate.

I know this will likely cause some headaches for people that have already started projects on CI4 beta, but this is the last expected breaking change prior to a RC (which is close!).


  Show ajax progress bar while uploading csv to db using jquery
Posted by: zeeshan - 06-12-2019, 04:11 AM - Forum: Regional User Groups - Replies (1)

I have uploaded csv to db some calculations are performed while uploading so it take 20 to 30 sec depending on csv file now i want to add ajax progress bar to be appeared while csv is being uploading in db and showing uploading percentage.
index.php

Code:
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Upload Attandance CSV</title>
  </head>
<body>
 <form id="attandance" action="" method="post" enctype="multipart/form-data" class="form-horizontal">
                    <div class="form-group">
                     <label class="col-md-4 control-label">Choose CSV File</label>
                     <input type="file" name="file" id="file" accept=".csv" class="form-control " placeholder="File">
                     <input type="submit" name="upload" id="upload" value="Import" class="btn btn-primary  offset-5"> </div>
                      <div id="loading" class="text-center mtop20"></div>
                      </form><br>
                       <div class="alert alert-success" style="display: none;"></div>
  <script src="<?php echo base_url(); ?>vendor/jquery/jquery.min.js"></script>
  <script src="<?php echo base_url(); ?>assets/js/demo/datatables-demo.js"></script>
<script>
  $(function(){
  $('#attandance').on('submit',function(e){
         e.preventDefault();
         $.ajax({
                 url:"<?php echo base_url(); ?>time/addcsv",
               method:"POST",
               data:new FormData(this),
               contentType:false,
               cache:false,
               processData:false,
                beforeSend: function() {
               var i='<img width="70" src="<?php echo base_url(); ?>/images/loadingImage.gif" />';    
                $("#loading").html(i);
                },
               success:function(respense){
                $("#loading").hide();
                $('.alert-success').html('Attandance Uploaded successfully').fadeIn().delay(4000).fadeOut('slow');
           }, error: function(){
                alert('Could not add data');
              }
           });
       });
  });
</script>
</body>
</html>

Controller

Code:
[b] [/b]public function addcsv(){
  $this->load->model('time_m','m');
         $result=$this->m->csv();
            $msg['success']=false;
                $msg['type']='add';
               if ($result){
               $msg['success']=true;
               }
              echo json_encode($msg);
  }

Model

Code:
public function csv(){
      $filename=explode(".",$_FILES["file"]["name"]);
      if(end($filename)=="csv"){
       $handle=fopen($_FILES["file"]["tmp_name"],"r");
       $m=$n=$u=$v=$z=$i='';$dg=1;$test=1;$first=false;
       while($data=fgetcsv($handle)){
        if(!$first){
            $first=true;
        }else{
        $emp_id=$data[0];$date=$data[1];$status=$data[2];
         $emp_rec =$this->db->get_where('nexthon_employ', array('employee_id'=>$emp_id));
         $happ_rec = $emp_rec->row(); $eid=$happ_rec->id ;$expectedMin= $happ_rec->workingHours*60;   
        $d=DateTime::createFromFormat("d-m-y H:i",$date);
        $a=$d->format("Y-m-d");$b=$d->format("H:i"); $month=$d->format("M"); $year=$d->format("Y");
        $rec=$this->db->get_where('csv', array('emp_id'=>$emp_id,'actiondate'=>$a));
        if($rec->num_rows()>0)
            {   
                $t=$rec->row();
                if($status==0 && $i!=0){
         $m=$b;$u=$v=null;$z=$t->totlbreak;
         $DateTime = new DateTime($b);
            $c=strtotime($DateTime->format("H:i"));
            $k=strtotime("13:00");
            if($c<=$k){
             $DateTime->modify('+4 hours');
              $n=$DateTime->format("H:i"); }
            else
              $n="17:00";
        }else if($status==1){
        $v=$t->breakOut;$z=$t->totlbreak;
         if($t->breakOut==$t->timeOut) 
         $v=$b; 
         $m=$t->timeIn;$u=$t->breakIn;$n=$b;
         if($i!=0){
            $DateTime = new DateTime($b);
            $c=strtotime($DateTime->format("H:i"));
            $k=strtotime("13:00");
            if($c>=$k){
             $DateTime->modify('-4 hours');
              $m=$DateTime->format("H:i");}
            else
              $m="09:00";
         $u=$v=null;$n=$b;
        } }
        else if($status==2 && $i==0){
        if($t->breakIn==null && $t->breakOut==null){ 
         $m=$t->timeIn;$u=$b;$v=$n=$t->timeOut;}
        else  if($t->breakIn!=null && $t->breakOut!=$t->timeOut){ 
         $m=$t->timeIn;$u=$b;$v=$n=$t->timeOut;
            $dteStart = new DateTime($t->breakIn); 
            $dteEnd   = new DateTime($t->breakOut); 
            $dteDiff  = $dteStart->diff($dteEnd); 
            $z=$dteDiff->format("%H:%I"); 
          if($t->totlbreak!=null){
            $time = $t->totlbreak;
            $time2 = $z;
            $secs = strtotime($time2)-strtotime("00:00");
            $z = date("H:i",strtotime($time)+$secs);
          }     }
        }else if($i==0 && $status==3 && $t->breakIn!=null){ $z=$t->totlbreak;
         $m=$t->timeIn;$v=$b;$u=$t->breakIn;
          $DateTime = new DateTime($b);
             $DateTime->modify('+1 minutes');
              $n=$DateTime->format("H:i");
        }
        $query=$this->db->query("UPDATE csv SET totlbreak='$z',timeIn='$m',timeOut='$n',breakIn='$u',breakOut='$v' WHERE `actiondate`='$a' AND `emp_id`='$emp_id'");
            }else{
     if($status==0){
         $m=$b;$u=$v=null;$i=0;
            $DateTime = new DateTime($b);
            $c=strtotime($DateTime->format("H:i"));
           $k=strtotime("13:00");
            if($c<=$k){
             $DateTime->modify('+4 hours');
              $n=$DateTime->format("H:i");}
            else
              $n="17:00";
          }
     else  if($status==1){
         $DateTime = new DateTime($b);
            $c=strtotime($DateTime->format("H:i"));
           $k=strtotime("13:00");
            if($c>=$k){
             $DateTime->modify('-4 hours');
              $m=$DateTime->format("H:i");}
            else
              $m="09:00";
         $u=$v=null;$n=$b;
        }
        $field=array(
        'eid'=>$eid,     
        'emp_id'=>$emp_id,
        'actiondate'=>$a,
        'type'=>'Working Day',
        'timeIn'=>$m,
        'timeOut'=>$n,
        'breakIn'=>$u,
        'breakOut'=>$v,
        'expectedMinutes'=>$expectedMin,
        'month'=>$month,
        'year'=>$year
        );
        $this->db->insert('csv',$field);$dg++;
            } }
        }fclose($handle);
        }
        if ( $this->db->affected_rows()>0) 
            return true;  
        else
            return false; 
     }


  error in Array to string conversion
Posted by: jackey - 06-11-2019, 10:41 PM - Forum: General Help - Replies (26)

hi,
I want to insert a new row to retire table at the same time when i insert a new row to employee table.

can anyone pls tell me how to fix these error?

/////view

Code:
  <div class="form-group">
       <label class="col-sm-2 control-label">Emp No.</label> <div class="col-sm-2"> <input type="text" name="emp_no" id="emp_no" class="form-control"/></div>
       <label class="col-sm-1 control-label">NIC</label> <div class="col-sm-2"> <input type="text" name="nic" id="nic" class="form-control"/></div>
       
   </div>

<div class="form-group"> <label class="col-sm-2 control-label">DOB</label>  
   <div class="col-sm-2" ><input type="date" class="form-control" id="dob" name="dob" /></div>
</div>


////controller

Code:
$data = array(        
'emp_no' => $this->input->post('emp_no'),
'nic' => $this->input->post('nic'),
'dob' => $this->input->post('dob'),
-----etc
);

$dob=strtotime($this->input->post('dob'));
$due_date_retire = date('Y-m-d', strtotime($dob . '+60 Years'));

$data_retire_tbl = array(  
'emp_no' => $this->input->post('emp_no'),
'due_date' => $due_date_retire  
);

$this->Model_user->model_add_new_emp($data,$data_retire_tbl);
$this->session->set_flashdata('message', ' Successfully ADDED New Employee ......');
echo json_encode(array("status" => TRUE));
 

////model
Code:
public function model_add_new_emp($data, $data_retire_tbl) {  
$this->db->insert('emp_pmt', $data);
$this->db->insert('retire', $data_retire_tbl);
return $this->db->insert_id();
       }



Attached Files Thumbnail(s)
           

  Issues with code
Posted by: Mekaboo - 06-11-2019, 10:04 PM - Forum: General Help - Replies (7)

Hello!

I would like to use this code for profile within my code but I get errors of undefinfed variables. Here is the code:

 <div class="avatar">

                            <img alt="<?php print $this->session->userdata('user_name'); ?>" src="<?php print HTTP_IMAGES_PATH; ?>user-default.jpg">
                        </div>
                    </div>
                    <div class="card-body info">
                        <div class="title">
                            <a href="<?php print site_url() ?>profile"><?php print $userInfo['full_name']; ?></a>
                        </div>
                        <div class="desc"> <a target="_blank" href="<?php print site_url(); ?>"><?php PRINT APPLICATION_NAME; ?></a></div>        
                        <div class="desc"><?php print $userInfo['email']; ?>, <?php print $userInfo['contact_no']; ?></div>      
                        <div class="desc"><?php print $userInfo['address']; ?></div>               

I get errors about the php but dont want to delete them because I feel its important. How do I edit the php inserts so they fit my code?

Heart Heart ,
Mekaboo


  $_FILES Array getting empty when using $this->form_validation->run()
Posted by: sarath_unrelax - 06-11-2019, 05:58 AM - Forum: Model-View-Controller - Replies (56)

Hello Everybody,

I have a controller called Home.php & I have method called addProperty() here process the image upload. But the problem is when i use the image upload code after $this->form_validation->run() , its not working.

But without $this->form_validation->run() , the image upload working. When i use the image upload code after the $this->form_validation->run() the image is not getting uploaded.

PHP Code:
   function addProperty()
 
   {




 
         $this->load->library('form_validation');

 
          //$this->form_validation->set_rules('prop_title','Villa Title','trim|required|max_length[128]');
 
         // $this->form_validation->set_rules('prop_status','Status','trim|required');
 
          //$this->form_validation->set_rules('prop_type','Type','trim|required');
 
          //$this->form_validation->set_rules('prop_price','Price','trim|required|numeric');
 
          //$this->form_validation->set_rules('prop_sqft','Sqft','trim|required|numeric');
 
          $this->form_validation->set_rules('prop_rooms','Rooms','trim|required|numeric');
 
          $this->form_validation->set_rules('prop_address','Address','trim|required|max_length[200]');
 
          $this->form_validation->set_rules('prop_owner_phone','Mobile Number','required|min_length[10]');
 
          $this->form_validation->set_rules('prop_owner_name','Owner Name','required|min_length[5]');
 
          $this->form_validation->set_rules('prop_owner_email','Owner Email','required|valid_email');
 
          //$this->form_validation->set_rules('prop_detailed_info','Detailed Info','trim|required|max_length[2000]');
 
          //$this->form_validation->set_rules('prop_status','Current Status','trim|required');




 
          if($this->form_validation->run() == FALSE)
 
          {
 
              $this->listProperty();
 
          }
 
          else
 
          {



 
              $prop_title ucwords(strtolower($this->security->xss_clean($this->input->post('prop_title'))));
 
              $prop_status ucwords(strtolower($this->security->xss_clean($this->input->post('prop_status'))));
 
              $prop_type ucwords(strtolower($this->security->xss_clean($this->input->post('prop_type'))));
 
              $prop_price $this->security->xss_clean($this->input->post('prop_price'));
 
              $prop_sqft $this->security->xss_clean($this->input->post('prop_sqft'));
 
              $prop_rooms $this->security->xss_clean($this->input->post('prop_rooms'));
 
              $prop_address $this->security->xss_clean($this->input->post('prop_address'));
 
              $prop_owner_name $this->security->xss_clean($this->input->post('prop_owner_name'));
 
              $prop_owner_email $this->security->xss_clean($this->input->post('prop_owner_email'));
 
              $prop_owner_phone $this->security->xss_clean($this->input->post('prop_owner_phone'));
 
              $prop_detailed_info $this->security->xss_clean($this->input->post('prop_detailed_info'));
 
              $prop_current_status $this->security->xss_clean($this->input->post('prop_current_status'));



 
              //$userInfo = array('email'=>$email, 'password'=>getHashedPassword($password), 'roleId'=>$roleId, 'name'=> $name,
 
                                  //'mobile'=>$mobile, 'createdBy'=>$this->vendorId, 'createdDtm'=>date('Y-m-d H:i:s'));

 
               $propertyInfo = array('title'=>$prop_title'status'=>$prop_status'type'=>$prop_type'price'=>$prop_price,
 
                                     'sqft'=>$prop_sqft'rooms'=>$prop_rooms'address'=>$prop_address'name'=>$prop_owner_name,
 
                                     'email'=>$prop_owner_email'phone'=>$prop_owner_phone'detailedInfo'=>$prop_detailed_info,
 
                                     'currentStatus'=>$prop_current_status);


 
              $this->load->model('property_model');
 
              $result $this->property_model->addNewProperty($propertyInfo);
 
            }


 
              if($result 0)
 
              {
 
                if (!empty($_FILES)) {
 
                $is_image "Yes";
 
                $count_img count($_FILES['file']['name']);

 
                foreach($_FILES['file']['tmp_name'] as $key => $value) {


 
                 $tempFile $_FILES['file']['tmp_name'][$key];
 
                 $fileName $_FILES['file']['name'][$key];
 
                 $targetPath 'property-images/';
 
                 $targetFile $targetPath $fileName ;
 
                 if(move_uploaded_file($tempFile$targetFile))
 
                 {

 
                     $imgData = array('path'=>$targetPath,'propertyid'=>$result);
 
                     $prop_push $this->property_model->addPropertyImgs($imgData);

 
                 }


 
                }
 
                }

 
                 //$propertyImgUpload = uploadImages($result);
 
                  $this->session->set_flashdata('success''Thank you for submiting.'.$result.'. your property!, Our team will contact you shortly');

 
              }
 
              else
 
              {
 
                  $this->session->set_flashdata('error''Submission of property failed, Contact [email protected]               }

               redirect('
/submit-property');








  Codeigniter 3 micro-blogging application architecture flaws
Posted by: Ajax30 - 06-11-2019, 12:15 AM - Forum: Best Practices - Replies (3)

I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.
The application allows Registration (as an author), Login, adding Categories and Posts.
I have created an installation process for the application: after creating a database and providing its credentials to the 

Code:
application/config/database.php

 file, you can run the 

Code:
Install

 controller which will create all the necessary tables:

Code:
class Install extends CI_Controller {
   public function __construct()
   {
       parent::__construct();
   }

   public function index(){
       // Create all the database tables if there are none
       // by redirecting to the Migrations controller
       $tables = $this->db->list_tables();
       if (count($tables) == 0) {
           redirect('migrate');
       } else {
           redirect('/');
       }
   }
}

After that, you can register as an author. Being the first registered author, you are also an admin, meaning that your author account does not require activation (and the value for the 
Code:
is_admin

 column has a value of 

Code:
1

 in the database record for you).

All the future authors will need their accounts activated by you in order to publish articles (posts).
It is a rather ambitious project, although I did not start it with great plans in mind. I just wanted to learn Codeigniter 3. You can see it on my GitHub account.
There are a few possible issues:
  1. The application does not use HMVC, but "classic" MVC.

  2. It does not have a clear separation between its front and its back (admin)

  3. I want to add a theming feature and I kinda got stuck with it; I don't know what approach to use.

  4. My controllers may be a over-coded.
Here is the 
Code:
Posts

 controller:

Code:
class Posts extends CI_Controller {

   public function __construct()
   {
       parent::__construct();
   }

   private function _initPagination($path, $totalRows, $query_string_segment = 'page') {
   //load and configure pagination
       $this->load->library('pagination');
       $config['base_url'] = base_url($path);
       $config['query_string_segment'] = $query_string_segment;
       $config['enable_query_strings'] =TRUE;
       $config['reuse_query_string'] =TRUE;
       $config['total_rows'] = $totalRows;
       $config['per_page'] = 12;
       if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
           $_GET[$config['query_string_segment']] = 1;
       }
       $this->pagination->initialize($config);

       $limit = $config['per_page'];
       $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;

       return ['limit' => $limit, 'offset' => $offset];
   }

   public function index() {

   //call initialization method
       $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

       $data = $this->Static_model->get_static_data();
       $data['pages'] = $this->Pages_model->get_pages();
       $data['categories'] = $this->Categories_model->get_categories();  

       //use limit and offset returned by _initPaginator method
       $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
       $this->load->view('partials/header', $data);
       $this->load->view('posts');
       $this->load->view('partials/footer');
   }

   public function search() {
   // Force validation since the form's method is GET
       $this->form_validation->set_data($this->input->get());
       $this->form_validation->set_rules('search', 'Search term', 'required|trim|min_length[3]',array('min_length' => 'The Search term must be at least 3 characters long.'));
       $this->form_validation->set_error_delimiters('<p class = "error search-error">', '</p>
           ');
       // If search fails
       if ($this->form_validation->run() === FALSE) {
           return $this->index();
       } else {
           $expression = $this->input->get('search');
           $posts_count = $this->Posts_model->search_count($expression);
           $query_string_segment = 'page';
           $config = $this->_initPagination("/posts/search", $posts_count, $query_string_segment);
           $data = $this->Static_model->get_static_data();
           $data['pages'] = $this->Pages_model->get_pages();
           $data['categories'] = $this->Categories_model->get_categories();
     //use limit and offset returned by _initPaginator method
           $data['posts'] = $this->Posts_model->search($expression, $config['limit'], $config['offset']);
           $data['expression'] = $expression;
           $data['posts_count'] = $posts_count;
           $this->load->view('partials/header', $data);
           $this->load->view('search');
           $this->load->view('partials/footer');
       }
   }

   public function byauthor($authorid){
       $data = $this->Static_model->get_static_data();
       $data['pages'] = $this->Pages_model->get_pages();
       $data['categories'] = $this->Categories_model->get_categories();
       $data['posts'] = $this->Posts_model->get_posts_by_author($authorid);
       $data['posts_count'] = $this->Posts_model->posts_by_author_count($authorid);
       $data['posts_author'] = $this->Posts_model->posts_author($authorid);

       $this->load->view('partials/header', $data);
       $this->load->view('posts_by_author');
       $this->load->view('partials/footer');
   }

   public function post($slug) {
       $data = $this->Static_model->get_static_data();
       $data['pages'] = $this->Pages_model->get_pages();
       $data['categories'] = $this->Categories_model->get_categories();
       $data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
       $data['post'] = $this->Posts_model->get_post($slug);

       if ($data['categories']) {
           foreach ($data['categories'] as &$category) {
               $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
           }
       }

       if (!empty($data['post'])) {
           // Overwrite the default tagline with the post title
           $data['tagline'] = $data['post']->title;

           // Get post comments
           $post_id = $data['post']->id;
           $data['comments'] = $this->Comments_model->get_comments($post_id);

           $this->load->view('partials/header', $data);
           $this->load->view('post');
       } else {
           $data['tagline'] = "Page not found";
           $this->load->view('partials/header', $data);
           $this->load->view('404');
       }
       $this->load->view('partials/footer');
   }

   public function create() {

       // Only logged in users can create posts
       if (!$this->session->userdata('is_logged_in')) {
           redirect('login');
       }

       $data = $this->Static_model->get_static_data();
       $data['pages'] = $this->Pages_model->get_pages();
       $data['tagline'] = "Add New Post";
       $data['categories'] = $this->Categories_model->get_categories();
       $data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);

       if ($data['categories']) {
           foreach ($data['categories'] as &$category) {
               $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
           }
       }

       $this->form_validation->set_rules('title', 'Title', 'required');
       $this->form_validation->set_rules('desc', 'Short description', 'required');
       $this->form_validation->set_rules('body', 'Body', 'required');
       $this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');

       if($this->form_validation->run() === FALSE){
           $this->load->view('partials/header', $data);
           $this->load->view('create-post');
           $this->load->view('partials/footer');
       } else {
           // Create slug (from title)
           $slug = url_title($this->input->post('title'), 'dash', TRUE);
           $slugcount = $this->Posts_model->slug_count($slug);
           if ($slugcount > 0) {
               $slug = $slug."-".$slugcount;
           }

           // Upload image
           $config['upload_path'] = './assets/img/posts';
           $config['allowed_types'] = 'jpg|png';
           $config['max_size'] = '2048';

           $this->load->library('upload', $config);

           if(!$this->upload->do_upload()){
               $errors = array('error' => $this->upload->display_errors());
               $post_image = 'default.jpg';
           } else {
               $data = array('upload_data' => $this->upload->data());
               $post_image = $_FILES['userfile']['name'];
           }

           $this->Posts_model->create_post($post_image, $slug);
           $this->session->set_flashdata('post_created', 'Your post has been created');
           redirect('/');
       }
   }

   public function edit($id) {
       // Only logged in users can edit posts
       if (!$this->session->userdata('is_logged_in')) {
           redirect('login');
       }

       $data = $this->Static_model->get_static_data();
       $data['pages'] = $this->Pages_model->get_pages();
       $data['categories'] = $this->Categories_model->get_categories();
       $data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
       $data['post'] = $this->Posts_model->get_post($id);
       if ($this->session->userdata('user_id') == $data['post']->author_id) {
           $data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
           $this->load->view('partials/header', $data);
           $this->load->view('edit-post');
           $this->load->view('partials/footer');
       } else {
           /* If the current user is not the author
           of the post do not alow edit */
           redirect('/' . $id);
       }
   }

   public function update() {
       // Form data validation rules
       $this->form_validation->set_rules('title', 'Title', 'required',  array('required' => 'The %s field can not be empty'));
       $this->form_validation->set_rules('desc', 'Short description', 'required',  array('required' => 'The %s field can not be empty'));
       $this->form_validation->set_rules('body', 'Body', 'required',  array('required' => 'The %s field can not be empty'));
       $this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');

       $id = $this->input->post('id');

       // Update slug (from title)
       if (!empty($this->input->post('title'))) {
           $slug = url_title($this->input->post('title'), 'dash', TRUE);
           $slugcount = $this->Posts_model->slug_count($slug);
           if ($slugcount > 0) {
               $slug = $slug."-".$slugcount;
           }
       } else {
           $slug = $this->input->post('slug');
       }

   // Upload image
       $config['upload_path'] = './assets/img/posts';
       $config['allowed_types'] = 'jpg|png';
       $config['max_size'] = '2048';

       $this->load->library('upload', $config);

       if ( isset($_FILES['userfile']['name']) && $_FILES['userfile']['name'] != null )
       {
           // Use name field in do_upload method
           if (!$this->upload->do_upload('userfile')) {
               $errors = array('error' => $this->upload->display_errors());

           } else {
               $data = $this->upload->data();
               $post_image = $data[ 'raw_name'].$data[ 'file_ext'];
           }
       }
       else {
           $post_image = $this->input->post('postimage');
       }


       if ($this->form_validation->run()) {
           $this->Posts_model->update_post($id, $post_image, $slug);
           $this->session->set_flashdata('post_updated', 'Your post has been updated');
           redirect('/' . $slug);
       } else {
           $this->form_validation->run();
           $this->session->set_flashdata('errors', validation_errors());
           redirect('/posts/edit/' . $slug);
       }
   }

   public function delete($slug) {
       // Only logged in users can delete posts
       if (!$this->session->userdata('is_logged_in')) {
           redirect('login');
       }

       $data['post'] = $this->Posts_model->get_post($slug);
       if ($this->session->userdata('user_id') == $data['post']->author_id)
     {
           $this->Posts_model->delete_post($slug);
           $this->session->set_flashdata('post_deleted', 'The post has been deleted');
           redirect('/');
       } else {
           /* If the current user is not the author
           of the post do not alow delete */
           redirect('/' . $slug);
       }
     }    
   }

Please help me with useful feedback and suggestions.


  Image upload using DropzoneJs how to post the file parameters to controller ?
Posted by: sarath_unrelax - 06-11-2019, 12:11 AM - Forum: Model-View-Controller - Replies (1)

Hello Everybody,

I'm first time here & also beginner to Codeigniter, I'm developing one website for a real estate agency & here I have one form to get property details such as property name, price,address,contact no etc from the user & also the images of property using the DropzoneJs.

I have two method in a controller :

addProperty() -  Here I validate the form inputs and insert into my table.

UploadImages() - Here I do upload process of the images.

But when I insert the property images details into table I need the reference of the property id which performed the insertion in addProperty() method. addProperty() method has $result variable which gives the last inserted id.
Once the insertion of property details is success I want to do the upload process of the property images and also insertion of image details into my table.

Here What is working :


1.Upload of images working
2. Insertion of property data working.

But what I actually need is, I wan't to process the images and property data in the same method called addProperty(), So I can get the reference of the last inserted id.



Controller
Name : Home.php 
Methods : addProperty() , uploadImages()


PHP Code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Class :Home (HomeController)
 * Login class to control to authenticate user credentials and starts user's session.
 * @author : Kishor Mali
 * @version : 1.1
 * @since : 15 November 2016
 */
class Home extends CI_Controller
{
 
   /**
     * This is default constructor of the class
     */
 
   public function __construct()
 
   {
 
     parent::__construct();
 
     $this->load->model('property_model');

 
    }

 
   /**
     * Index Page for this controller.
     */
 
   public function index()
 
   {
 
       $data = array('title'=> 'Vierra Property Broker''main_content'=>'home');
 
       $this->load->view('template'$data);

 
   }

 
   /**
     * Loaading the submit property form.
     */

 
   public function listProperty()

 
   {

 
     $data = array('title'=> 'Vierra Property Broker - Submit your Property''main_content'=>'submit_property');
 
     $this->load->view('template'$data);




 
   }



 
   function addProperty()
 
   {

 
          $this->load->library('form_validation');

 
          //$this->form_validation->set_rules('prop_title','Villa Title','trim|required|max_length[128]');
 
         // $this->form_validation->set_rules('prop_status','Status','trim|required');
 
          //$this->form_validation->set_rules('prop_type','Type','trim|required');
 
          //$this->form_validation->set_rules('prop_price','Price','trim|required|numeric');
 
          //$this->form_validation->set_rules('prop_sqft','Sqft','trim|required|numeric');
 
          $this->form_validation->set_rules('prop_rooms','Rooms','trim|required|numeric');
 
          $this->form_validation->set_rules('prop_address','Address','trim|required|max_length[200]');
 
          $this->form_validation->set_rules('prop_owner_phone','Mobile Number','required|min_length[10]');
 
          $this->form_validation->set_rules('prop_owner_name','Owner Name','required|min_length[5]');
 
          $this->form_validation->set_rules('prop_owner_email','Owner Email','required|valid_email');
 
          //$this->form_validation->set_rules('prop_detailed_info','Detailed Info','trim|required|max_length[2000]');
 
          //$this->form_validation->set_rules('prop_status','Current Status','trim|required');

 
          if($this->form_validation->run() == FALSE)
 
          {
 
              $this->listProperty();
 
          }
 
          else
 
          {


 
              $prop_title ucwords(strtolower($this->security->xss_clean($this->input->post('prop_title'))));
 
              $prop_status ucwords(strtolower($this->security->xss_clean($this->input->post('prop_status'))));
 
              $prop_type ucwords(strtolower($this->security->xss_clean($this->input->post('prop_type'))));
 
              $prop_price $this->security->xss_clean($this->input->post('prop_price'));
 
              $prop_sqft $this->security->xss_clean($this->input->post('prop_sqft'));
 
              $prop_rooms $this->security->xss_clean($this->input->post('prop_rooms'));
 
              $prop_address $this->security->xss_clean($this->input->post('prop_address'));
 
              $prop_owner_name $this->security->xss_clean($this->input->post('prop_owner_name'));
 
              $prop_owner_email $this->security->xss_clean($this->input->post('prop_owner_email'));
 
              $prop_owner_phone $this->security->xss_clean($this->input->post('prop_owner_phone'));
 
              $prop_detailed_info $this->security->xss_clean($this->input->post('prop_detailed_info'));
 
              $prop_current_status $this->security->xss_clean($this->input->post('prop_current_status'));









 
              //$userInfo = array('email'=>$email, 'password'=>getHashedPassword($password), 'roleId'=>$roleId, 'name'=> $name,
 
                                  //'mobile'=>$mobile, 'createdBy'=>$this->vendorId, 'createdDtm'=>date('Y-m-d H:i:s'));

 
               $propertyInfo = array('title'=>$prop_title'status'=>$prop_status'type'=>$prop_type'price'=>$prop_price,
 
                                     'sqft'=>$prop_sqft'rooms'=>$prop_rooms'address'=>$prop_address'name'=>$prop_owner_name,
 
                                     'email'=>$prop_owner_email'phone'=>$prop_owner_phone'detailedInfo'=>$prop_detailed_info,
 
                                     'currentStatus'=>$prop_current_status);


 
              $this->load->model('property_model');
 
              $result $this->property_model->addNewProperty($propertyInfo);

 
              if($result 0)

 
              {

 
                 //$propertyImgUpload = uploadImages($result);
 
                  $this->session->set_flashdata('success''Thank you for submiting your property with us!, Our team will contact you shortly');
 
              }
 
              else
 
              {
 
                  $this->session->set_flashdata('error''Submission of property failed, Contact [email protected]');
 
              }

 
              redirect('/submit-property');
 
          }





}

function 
uploadImages()
{


 
       if (!empty($_FILES)) {
 
       $count_img count($_FILES['file']['name']);

 
     foreach($_FILES['file']['tmp_name'] as $key => $value) {


 
       $tempFile $_FILES['file']['tmp_name'][$key];
 
       $fileName $_FILES['file']['name'][$key];
 
       $targetPath 'property-images/';
 
       $targetFile $targetPath $fileName ;
 
       if(move_uploaded_file($tempFile$targetFile))



 
       {





 
         echo "Success";

 
       }

 
       else {

 
         echo "Failed";

 
       }
 
  }

}

}
}

?>


View

Name : submit_property.php

PHP Code:
<div class="content-area-7 submit-property">
 
   <div class="container">
 
       <div class="row">
 
           <div class="col-md-12">

 
         <!--      <div id="error_message" class="notification-box"></div> -->





 
           </div>

 
           <?php
                $this
->load->helper('form');






 
               $error $this->session->flashdata('error');
 
               if($error)
 
               {
 
                 echo '<div class="notification-box">'.$error.'</div>';

 
               }

 
               $success $this->session->flashdata('success');
 
               if($success)
 
               {
 
                 echo '<div class="notification-box">'.$success.'</div>';

 
               }

 
               ?>

                <div id="error_msg" class="alert alert-danger wow fadeInRight delay-01s" role="alert" style="visibility: visible; animation-name: fadeInRight;">
                  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
                  <strong>Oops!</strong>, Please fix the following errors and submit again
                </div>

            <div class="col-md-12">
                <div class="submit-address">


                    <form name="property-form" action="<?php echo base_url() ?>list-property" enctype="multipart/form-data" method="post" id="property-form">
                        <div class="main-title-2">
                            <h1><span>Tell Me</span> Something About Your Property</h1>
                        </div>
                        <div class="search-contents-sidebar mb-30">
                            <div class="form-group">
                                <label>Property Title</label>

                                <input class="input-text" name="prop_title" id="prop_title" placeholder="Property Title">
                                <?php echo form_error('prop_title'); ?>
                            </div>

                            <div class="row">
                                <div class="col-md-6 col-sm-6">
                                    <div class="form-group">
                                        <label>Status</label>
                                        <select class="form-control required" id="prop_status" name="prop_status">
                                          <option value="">Select</option>
                                            <option value="Sale">For Sale</option>
                                            <option value="Rent">For Rent</option>
                                        </select>

                                    </div>

                                </div>
                                <div class="col-md-6 col-sm-6">
                                    <div class="form-group">
                                        <label>Type</label>
                                        <select class="form-control required" id="prop_type" name="prop_type">
                                          <option value="">Select</option>
                                            <option value="Modern">Modern</option>
                                            <option value="Traditional">Traditional</option>
                                            <option value="Arabic">Arabic</option>

                                        </select>


                                    </div>

                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-3 col-sm-6">
                                    <div class="form-group">
                                        <label>Price (Dirham)</label>
                                        <input class="input-text" name="prop_price" id="prop_price" placeholder="AED">
                                        <?php echo form_error('prop_price'); ?>

                                    </div>
                                </div>
                                <div class="col-md-3 col-sm-6">
                                    <div class="form-group">
                                        <label>Sqft</label>
                                        <input class="input-text" name="prop_sqft" id="prop_sqft" placeholder="SqFt">
                                        <?php echo form_error('prop_sqft'); ?>


                                    </div>
                                </div>
                                <div class="col-md-3 col-sm-6">
                                    <div class="form-group">
                                        <label>Bed Rooms</label>
                                        <select class="form-control required" name="prop_rooms" id="prop_rooms">
                                            <option value="">Select</option>
                                            <option value="3">3</option>
                                            <option value="4">4</option>
                                            <option value="5">5</option>

                                        </select>


                                    </div>
                                </div>
                                <!-- <div class="col-md-3 col-sm-6">
                                    <div class="form-group">
                                        <label>Bathroom</label>
                                        <select class="selectpicker search-fields" name="1">
                                            <option>1</option>
                                            <option>2</option>
                                            <option>3</option>
                                            <option>4</option>
                                            <option>5</option>
                                            <option>6</option>
                                        </select>
                                    </div>
                                </div> -->
                            </div>
                        </div>


                        <div class="main-title-2">
                            <h1><span>Location</span></h1>
                        </div>
                        <div class="row mb-30 ">
                            <div class="col-md-6 col-sm-6">
                                <div class="form-group">
                                    <label>Address</label>
                                    <input class="input-text" id="prop_address" name="prop_address"  placeholder="Address">
                                </div>
                                <?php echo form_error('prop_address'); ?>


                            </div>



                        </div>
                        <div class="main-title-2">
                            <h1><span>Contact</span> Details</h1>
                        </div>
                        <div class="row">
                            <div class="col-md-4 col-sm-4">
                                <div class="form-group">
                                    <label>Name</label>
                                    <input class="input-text" name="prop_owner_name" id="prop_owner_name" placeholder="Name">
                                    <?php echo form_error('prop_owner_name'); ?>

                                </div>
                            </div>
                            <div class="col-md-4 col-sm-4">
                                <div class="form-group">
                                    <label>Email</label>
                                    <input class="input-text" name="prop_owner_email" id="prop_owner_email" placeholder="Email">
                                    <?php echo form_error('prop_owner_email'); ?>

                                </div>
                            </div>

                            <div class="col-md-4 col-sm-4">
                                <div class="form-group">
                                    <label>Contact No</label>
                                    <input class="input-text" name="prop_owner_phone" id="prop_owner_phone" placeholder="Phone">
                                    <?php echo form_error('prop_owner_phone'); ?>

                                </div>
                            </div>



                            </div>


                        <div class="main-title-2">
                        <h1><span>Upload</span> Photos Of Villa </h1>
                        </div>

                        <div id="myDropzone" class="dropzone dropzone-design mb-10">
                          <div class="dz-default dz-message" data=""><span>Drop files here to upload</span></div>
                                                </div>

                        <div class="main-title-2">
                            <h1><span>Detailed</span> Information</h1>
                        </div>



                        <div class="row mb-30">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <textarea class="input-text" id="prop_detailed_info" name="prop_detailed_info" placeholder="Detailed Information"></textarea>
                                </div>
                                <?php echo form_error('prop_detailed_info'); ?>
                            </div>
                        </div>




                          </div>



                            <div class="col-md-12">
                              <button type="submit" id="submit-all" class="btn button-sm button-theme">Submit
                            </button>

                            </div>
                            <script src="<?php echo base_url('assets/frontend/js/addProperty.js'); ?>"></script>

                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div> 


Jquery (Perform dropzone upload)

Code:
/**
* File : addUser.js
*
* This file contain the validation of add user form
*
* Using validation plugin : jquery.validate.js
*
* @author Sarath Chandran
*/

 $(document).ready(function(){

   $("#error_msg").hide();


     var addPropertyForm = $("#property-form");

     var validator = addPropertyForm.validate({

        rules:{
            //prop_title :{ required : true },
            //prop_status : { required : true, selected : true },
            //prop_type : {required : true, selected: true },
     prop_rooms : {required : true, selected: true },
     prop_address :{ required : true },
     prop_owner_name :{ required : true },
     //prop_detailed_info :{ required : true },
     prop_owner_email :{ required : true, email : true },
     prop_owner_phone :{ required : true, digits : true },
            //prop_price : { required : true, digits : true },
     //prop_sqft : { required : true, digits : true }


        },
        messages:{
            //prop_title :{ required : "Please enter title of villa" },
            //prop_status : { required : "Please select status", selected : "Please select atlease one option" },
     //prop_type : { required : "Please select type of villa", selected : "Please select atlease one option" },
     prop_rooms : { required : "Please select bed rooms", selected : "Please select atlease one option" },
            prop_address : { required : "Please enter address of villa"},
     prop_owner_name : { required : "Please enter name of owner"},
     prop_owner_email : { required : "Please enter email of owner", email : "Please enter valid email"},
     prop_owner_phone : { required : "Please enter phone of owner", digits : "Please enter valid phone no"},
     //prop_price : { required : "Please enter price of villa", digits : "Please enter price in digits"},
     //prop_detailed_info : { required : "Please enter detailed information"},
     //prop_sqft : { required : "Please enter size of villa", digits : "Please enter size in Sqft"}

        },



})



Dropzone.autoDiscover = false;

   $("div#myDropzone").dropzone({

       url: 'image-upload',
       addRemoveLinks: true,
       paramName: "file",
       maxFiles:11,
       autoProcessQueue: false,
       uploadMultiple: true,
       acceptedFiles: "image/*",
       maxFilesize: 1,
       parallelUploads: 10,

       init: function () {

           var myDropzone = this;

           document.getElementById("submit-all").addEventListener("click", function(e) {
                       // Make sure that the form isn't actually being sent.
                       e.preventDefault();



             $(window).scrollTop(0);

             //e.preventDefault();

             if ( $("#property-form").valid() ) {
               myDropzone.processQueue();

             }

             });





           this.on('sending', function(data, xhr, formData) {
           formData.append("prop_title", jQuery("#prop_title").val());
           formData.append("prop_title", jQuery("#prop_title").val());

                 alert("Data is sending");

           });

           this.on("sendingmultiple", function(data, xhr, formData) {
           formData.append("prop_title", jQuery("#prop_title").val());
           formData.append("prop_title", jQuery("#prop_title").val());

       });

           this.on("complete", function (file) {
             if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {

                 alert("Completed Upload");
                 //$("#property-form").submit();
           }

         });






 }



});


});



Routes

Code:
$route['image-upload'] = 'home/uploadImages';

How I can process the form inputs and image data in the same method called addProperty() ?


  Error in query
Posted by: pedrossjr - 06-10-2019, 11:17 AM - Forum: Model-View-Controller - Replies (1)

Hi, i am trying to do this query in my model

$this->db->select( "r.cod_colaborador, r.cod_supervisor" );
$this->db->from( "tbl_rhm_colaboradores as r" );
$this->db->where( "r.sit_cadastro", "A" );
$this->db->order_by( "r.cod_supervisor, r.cod_colaborador asc" );
$subQuery1 = $this->db->get_compiled_select();

$this->db->select( "cod_colaborador" );
$this->db->from( "( ". $subQuery1 . " ) as tbl_cad_corretores, ( SELECT @pv := " . $cod_colaborador . " ) initialisation" );
$this->db->group_start();
$this->db->where( "find_in_set( cod_supervisor, @pv ) > 0" );
$this->db->where( "@pv := CONCAT( @pv, ',', cod_colaborador )" );
$this->db->group_end();
$this->db->or_where( "cod_colaborador = @pv" );
$subQuery2 = $this->db->get_compiled_select();

$this->db->from( $this->tabela );
$this->db->select( 'cli.num_cpf, cli.nom_cliente, c1.nom_apelido, c2.nom_apelido as nom_gerente, cli.sit_cadastro, cli.cod_usuario' );
$this->db->join( 'tbl_rhm_colaboradores c1','c1.cod_colaborador = cli.cod_corretor', 'inner' );
$this->db->join( 'tbl_rhm_colaboradores c2','c2.cod_colaborador = c1.cod_supervisor', 'left' );
$this->db->where_in( "cli.cod_corretor", $subQuery2, false );


But have a error 

ERROR - 2019-06-10 14:00:23 --> Query error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '`:` = CONCAT( @pv, ',', cod_colaborador)
 )
OR `cod_colaborador` = `@pv`)
ORDER ' at line 12 - Invalid query: SELECT `cli`.`num_cpf`, `cli`.`nom_cliente`, `c1`.`nom_apelido`, `c2`.`nom_apelido` as `nom_gerente`, `cli`.`sit_cadastro`, `cli`.`cod_usuario`
FROM `tbl_cad_clientes` `cli`
INNER JOIN `tbl_rhm_colaboradores` `c1` ON `c1`.`cod_colaborador` = `cli`.`cod_corretor`
LEFT JOIN `tbl_rhm_colaboradores` `c2` ON `c2`.`cod_colaborador` = `c1`.`cod_supervisor`
WHERE cli.cod_corretor IN(SELECT `cod_colaborador`
FROM ( SELECT `r`.`cod_colaborador`, `r`.`cod_supervisor`
FROM `tbl_rhm_colaboradores` as `r`
WHERE `r`.`sit_cadastro` = 'A'
ORDER BY `r`.`cod_supervisor`, `r`.`cod_colaborador` asc ) as tbl_cad_corretores, ( SELECT @pv := 214 ) initialisation
WHERE   (
find_in_set( cod_supervisor, @pv ) >0
AND `@pv` `:` = CONCAT( @pv, ',', cod_colaborador)
 )
OR `cod_colaborador` = `@pv`)
ORDER BY `cli`.`nom_cliente` ASC
 LIMIT 10

The error is `@pv` `:` = 

and 

OR `cod_colaborador` = `@pv`)

The Correct is to

@pv := 
and 

`cod_colaborador` = @pv)

How to resolve this?


  MongoDB
Posted by: omid_student - 06-10-2019, 06:37 AM - Forum: General Help - No Replies

Hi
How do can i use MongoDB in Codeigniter?
It is good database for big data
I download below library for Codeigniter but there is a problem about mongo db class

Thanks



  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.