Pagination codeigniter with query search - codeigniter

i want to create codeigniter pagination in my search form, when i clicked submit,it successfully shows the query search but when i clicked the number page link or next page, it shows message "undefined variable rec" and "Fatal error: Call to a member function num_rows() on a non-object" ,i'm sure the query has been passed to variable $rec.
And i see the problem here when i change the page,the variable return to null, so variable $rec didn't get the value from 'post'.
my question: how do i keep the value from 'post' so the query will get the variable value when i change the page?
here is my controller:
public function search(){
$kat=$this->input->post('kategori');
$prov=$this->input->post('prov');
$kot=$this->input->post('kota');
if($kat=='' && $prov!='' && $kot!=''){
$rec=$this->db->query("select * from showall where id_prov='$prov' and id_kota='$kot' ");
}
else if($kot=='' && $kat!='' && $prov!=''){
$rec=$this->db->query("select * from showall where id_kat='$kat' and id_prov='$prov' ");
}
else if($kat=='' && $kot=='' && $prov!=''){
$rec=$this->db->query("select * from showall where id_prov='$prov' ");
}
else if($kat!='' && $prov=='' && $kot==''){
$rec=$this->db->query("select * from showall where id_kat='$kat' ");
}
else if($kat!='' && $prov!='' && $kot!=''){
$rec=$this->db->query("select * from showall where id_kat='$kat' and id_prov='$prov' and id_kota='$kot' ");
}
$dat=$rec;
$data['count']=$dat->num_rows();
if($data['count'] >0){
$data['db']=$rec;
$config['total_rows'] = $data['db']->num_rows();
$config['base_url'] = base_url().'index.php/lowongan/cari';
$config['per_page'] = 1;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$data['paging'] = $this->pagination->create_links();
if($kat=='' && $prov!='' && $kot!=''){
$d = $this->db->get_where('showall',array('id_prov'=>$prov,'id_kota'=>$kot) ,$config['per_page'], $this->uri->segment(3));
}
else if($kot=='' && $kat!='' && $prov!=''){
$d= $this->db->get_where('showall',array('id_kat'=>$kat,'id_prov'=>$prov) ,$config['per_page'], $this->uri->segment(3));
}
else if($kat=='' && $kot=='' && $prov!=''){
$d = $this->db->get_where('showall',array('id_prov'=>$prov) ,$config['per_page'], $this->uri->segment(3));
}
if($kat!='' && $prov=='' && $kot==''){
$d = $this->db->get_where('showall',array('id_kat'=>$kat) ,$config['per_page'], $this->uri->segment(3));
}
else if($kat!='' && $prov!='' && $kot!=''){
$d = $this->db->get_where('showall',array('id_kat'=>$kat,'id_prov'=>$prov,'id_kota'=>$kot) ,$config['per_page'], $this->uri->segment(3));
}
$data['record']=$d;
$data1['kat']=$this->query->kategoriAll();
$data1['prov']=$this->query->showProv();
$data['q1']=$this->query->lokasi();
$data['q2']=$this->query->perusahaan();
$data['q3']=$this->query->kategori();
$this->load->view("user/head");
$this->load->view("user/bar",$data1);
$this->load->view( 'user/hal_cari',$data);
$this->load->view("user/footer");
}
else{
$data1['kat']=$this->query->kategoriAll();
$data1['prov']=$this->query->showProv();
$data['q1']=$this->query->lokasi();
$data['q2']=$this->query->perusahaan();
$data['q3']=$this->query->kategori();
$this->load->view("user/head");
$this->load->view("user/bar",$data1);
$this->load->view( 'user/kosong',$data);
$this->load->view("user/footer");
}
}

You need to keep the condition array in the URL using assoc_to_uri(). I am doing like below.
$this->load->model('classified_model','classified');
$ClassifiedList = $this->classified->searchPage($condition,'classified_view',$perPage,$page*$perPage);
$uriString = $this->uri->assoc_to_uri($condition);
$config['uri_segment'] = count($condition) * 2 + 4;
$base_url = site_url('classified/search/' . $uriString . '/page/');
$base_url = preg_replace("/\.[a-z]*$/","", $base_url);
$config['base_url'] = $base_url;
$config['per_page'] = 1;
To get the $condition from uri again use
$condition = $this->uri->uri_to_assoc();

Related

Refactor Laravel Eloquent Query

I want to filter data given from eloquent laravel. I have 4 date picker in my view, and I want when each of one has filled and has date the query change.
This is my code in controller
if ($start_publish && $end_publish && $start_close && $end_close) {
$data = Tender::where('published_at','>=',$start_publish)->where('published_at','<=',$end_publish)->where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);
}elseif (!$start_publish && $end_publish && $start_close && $end_close) {
$data = Tender::where('published_at','<=',$end_publish)->where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);
} elseif ($start_publish && !$end_publish && $start_close && $end_close) {
$data = Tender::where('published_at','>=',$start_publish)->where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);
} elseif (!$start_publish && !$end_publish && $start_close && $end_close) {
$data = Tender::where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);
} elseif ($start_publish && $end_publish && !$start_close && $end_close) {
$data = Tender::where('published_at','>=',$start_publish)->where('published_at','<=',$end_publish)->where('closed_at','<=',$end_close);
}
elseif ($start_publish && $end_publish && $start_close && !$end_close) {
...
...
...
} else {
$data = Tender::get();
}
Because I have 4 input, the number of states for the condition is equal to 16 and the code is messy.
Does anyone have an idea to refactor the code?
The idea: if your variable is set, you check it. Otherwise not
You could try with this ( this is an idea, not the actual code )
$builder = Tender::query();
if($start_publish) $builder->where('published_at','>=',$start_publish);
if($start_close) $builder->where('closed_at','>=',$start_close);
...
return $builder->get()
.... and so on

How to add another array value in codeigniter using getRecords

The orignial code was like this , I want to get landline_no value also in getRecords, How to do that
public function checklead() {
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead));
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead));
if($lead->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';}
What I have achieved so far,but not getting array values from getRecords
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead),array("landline_no"=>$lead));
//echo "<pre>";
//print_r($check);
//echo $check[0]['landline_no'];exit;
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead,"landline_no"=>$check[0]['landline_no']));
Code for getRecords:
function getRecords($table,$db = array(),$select = "*",$ordercol = '',$group = '',$start='',$limit=''){
$this->db->select($select);
if(!empty($ordercol)){
$this->db->order_by($ordercol);
}
if($limit != '' && $start !=''){
$this->db->limit($limit,$start);
}
if($group != ''){
$this->db->group_by($group);
}
$q=$this->db->get_where($table, $db);
return $q->result_array();
}
// Get Recored row
public function getRecored_row($table,$where)
{
$q = $this->db->where($where)
->select('*')
->get($table);
return $q->row();
}
Check my answer: This code also working well, i have written, but i am not sure , this logic is correct or not kindly check this one.
public function checklead() {
$lead = $_POST['number'];
if($this->common_model->getRecords('leads',array("phone_no"=>$lead)))
{
$check=$this->common_model->getRecords('leads',array("phone_no"=>$lead));
}
else
{
$check=$this->common_model->getRecords('leads',array("landline_no"=>$lead));
}
echo "<pre>";
//echo $check;
//print_r($check); exit;
$p= $check[0]['phone_no'];
$l= $check[0]['landline_no'];
// exit;
if(count($p) > 0 || count($l)>0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$p));
$lead1 = $this->common_model->getRecored_row('leads',array("landline_no"=>$l));
if($lead->assignto_self != 0 || $lead1->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0 || $lead1->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';
}else if($lead->assignto_tl != 0 || $lead1->assignto_tl != 0) {
$assignto = $lead->assignto_tl;
$key = '';
} else if($lead->uploaded_by != 0 || $lead1->uploaded_by != 0) {
$assignto = $lead->uploaded_by;
$key = 'Uploaded by';
}
$user = $this->common_model->getRecored_row('admin',array("id"=>$assignto));
$role = $this->common_model->getRecored_row('role',array("id"=>$user->role));
$this->session->set_flashdata('message', array('message' => 'This Lead Already exist with '.$user->name.' ('.$role->role.') '.' ','class' => 'danger'));
redirect(base_url().'leads');
} else {
redirect(base_url().'leads/add_newlead/'.$lead);
}
}
There does not seem to be any reason to use getRecords(). The $check value has no useful purpose and creating it is a waste of resources.
We don't need $check because getRecord_row() will return the "lead" if found so the only check needed is to see if getRecord_row() returns anything. getRecord_row() uses the database function row() which returns only one row or null if no rows are found. Read about row() here.
If what you want is to find the "lead" that has either a "phone_no" or a "landline_no" equal to $_POST['number'] then you need to use a custom string for the where clause. (See #4 at on this documentation page.) You need a custom string because getRecord_row() does not allow any other way to ask for rows where a='foo' OR b='foo'. Here is what I think you are looking for.
public function checklead()
{
// use input->post() it is the safe way to get data from $_POST
$phone = $this->input->post('number');
// $phone could be null if $_POST['number'] is not set
if($phone)
{
$lead = $this->common_model->getRecored_row('leads', "phone_no = $phone OR landline_no = $phone");
// $lead could be null if nothing matches where condition
if($lead)
{
if($lead->assignto_self != 0)
{
$assignto = $lead->assignto_self;
$key = 'Self Assign';
}
else if($lead->assignto_se != 0)
{
$assignto = $lead->assignto_se;
$key = '';
}
}
}
}
The main difference between getRecords() and getRecord_row() is the number of records (rows of data) to return. getRecord_row() will return a maximum of one record while getRecords() might return many records.
getRecords() accepts arguments that allow control of what data is selected ($db, $select), how it is arranged ($ordercol, $group), and the number of rows to retrieve ($limit) starting at row number x ($start) .

Unink log files that were created the day before in codeigniter

I am trying to unlink files that were created the day before
I have a custom application > core > MY_Log.php file and it creates a log for each error level. For easier reading.
logs > DEBUG-04-08-2016.php
logs > ERROR-04-08-2016.php
logs > INFO-04-08-2016.php
logs > DEBUG-03-08-2016.php
logs > ERROR-03-08-2016.php
logs > INFO-03-08-2016.php
Question how am I able to modify the write_log so could delete / unlink files that were created the day before?
<?php
class MY_Log extends CI_Log {
public function write_log($level, $msg)
{
if ($this->_enabled === FALSE)
{
return FALSE;
}
$level = strtoupper($level);
if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
&& ! isset($this->_threshold_array[$this->_levels[$level]]))
{
return FALSE;
}
$filepath = $this->_log_path . $level .'-'. date('d-m-Y').'.'.$this->_file_ext;
$message = '';
if ( ! file_exists($filepath))
{
$newfile = TRUE;
// Only add protection to php files
if ($this->_file_ext === 'php')
{
$message .= "";
}
}
if ( ! $fp = #fopen($filepath, 'ab'))
{
return FALSE;
}
flock($fp, LOCK_EX);
// Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
if (strpos($this->_date_fmt, 'u') !== FALSE)
{
$microtime_full = microtime(TRUE);
$microtime_short = sprintf("%06d", ($microtime_full - floor($microtime_full)) * 1000000);
$date = new DateTime(date('d-m-Y H:i:s.'.$microtime_short, $microtime_full));
$date = $date->format($this->_date_fmt);
}
else
{
$date = date($this->_date_fmt);
}
$message .= $this->_format_line($level, $date, $msg);
for ($written = 0, $length = strlen($message); $written < $length; $written += $result)
{
if (($result = fwrite($fp, substr($message, $written))) === FALSE)
{
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
if (isset($newfile) && $newfile === TRUE)
{
chmod($filepath, $this->_file_permissions);
}
return is_int($result);
}
}
First of use
$config['log_threshold'] = 1;
For only error message, so there will be less number of files
Add below code just before $filepath; to delete previous date logs
$unlink_date = date('Y-m-d',strtotime("-1 days"));
$filepath_unlink = $this->_log_path . $level .'-'. $unlink_date.'.'.$this->_file_ext;
if ( file_exists($filepath_unlink))
{
unlink($filepath_unlink);
}

CI pagination double query

I am working in CI Framework. For pagination i use two queries, one for required output using limit, and another to count total number of rows. Is there any other way like both can be done from single query?
My query is:
{
$searchtxt = $this->input->post('searchtxt');
$datefrom = $this->input->post('fromdate');
$todate = $this->input->post('todate');
$status= $this->input->post('order_status');
$sc_id = $this->input->post('sc_id');
if($sc_id){
$this->db->where('('.'o.requested_sc_id = '.$sc_id.' OR o.requesting_sc_id = '.$sc_id.')');
//$this->db->where('o.requesting_sc_id =',$sc_id);
}
if ($status){
$this->db->where('o.order_status =',$status);
}
if ($status != '' && $status == 0 ){
$this->db->where('o.order_status = 0');
}
if($searchtxt){
$this->db->like('o.order_number',$searchtxt);
}
if($datefrom)
{
$this->db->where('o.order_dt >=', date("Y-m-d",date_to_timestamp($datefrom)));
}
if($todate)
{
$this->db->where('o.order_dt <=', date("Y-m-d",date_to_timestamp($todate)));
}
if ($this->session->userdata('usergroup_id')!=1 && $this->session->userdata('usergroup_id')!= 2 && $this->session->userdata('usergroup_id')!=6 ){
$this->db->where('('.'o.requested_sc_id = '.$this->session->userdata('sc_id').' OR o.requesting_sc_id = '.$this->session->userdata('sc_id').')');
//$this->db->where('o.requesting_sc_id = '.$this->session->userdata('sc_id'));
}
$this->db->select('o.order_id,o.order_number,o.order_dt,o.call_id,c.call_uid,o.order_status,o.order_dt,sc.sc_name,e.engineer_name');
$this->db->from($this->table_name.' AS o');
$this->db->join($this->mdl_callcenter->table_name.' AS c','c.call_id=o.call_id','left');
$this->db->join($this->mdl_servicecenters->table_name.' AS sc' ,'sc.sc_id=o.requested_sc_id','left');
$this->db->join($this->mdl_engineers->table_name.' AS e', 'e.engineer_id = o.engineer_id','left');
$this->db->order_by('o.order_status ASC,o.order_dt DESC,o.order_created_ts DESC');
if(isset($page['limit'])){
$this->db->limit((int)$page['limit'],(int)$page['start']);
}
$result = $this->db->get();
//echo $this->db->last_query();
if ($status){
$this->db->where('o.order_status =',$status);
}
if ($status != '' && $status == 0 ){
$this->db->where('o.order_status = 0');
}
if($sc_id){
$this->db->where('o.requesting_sc_id =',$sc_id);
}
if($searchtxt){
$this->db->like('o.order_number',$searchtxt);
}
if($datefrom)
{
$this->db->where('o.order_dt >=', date("Y-m-d",date_to_timestamp($datefrom)));
}
if($todate)
{
$this->db->where('o.order_dt <=', date("Y-m-d",date_to_timestamp($todate)));
}
//if ($this->session->userdata('global_admin')!=1){
if ($this->session->userdata('usergroup_id')!=1 && $this->session->userdata('usergroup_id')!= 2 && $this->session->userdata('usergroup_id')!=6 ){
$this->db->where('o.requested_sc_id = '.$this->session->userdata('sc_id').' or o.requesting_sc_id = '.$this->session->userdata('sc_id'));
}
$this->db->select('o.order_id');
$this->db->from($this->table_name.' AS o');
$this->db->join($this->mdl_callcenter->table_name.' AS c','c.call_id=o.call_id','left');
$this->db->join($this->mdl_servicecenters->table_name.' AS sc' ,'sc.sc_id=o.requested_sc_id','left');
$this->db->join($this->mdl_engineers->table_name.' AS e', 'e.engineer_id = o.engineer_id','left');
$result_total = $this->db->get();
$orders['list'] = $result->result();
$orders['total'] = $result_total->num_rows();
return $orders;
}
Here is some explanation for this.
function($limit,$offset){
$this->db
->select("SQL_CALC_FOUND_ROWS emp", FALSE)
->select("*")
->from('tbl1')
->limit($limit, $offset);
$data["query_result"] = $this->db->get()->result_array();
$query = $this->db->query('SELECT FOUND_ROWS() AS `Count`');
$data["total_rows"] = $query->row()->Count;
return $data;
}
Here you see you are forced to get total count using another query.
Of course this is not what you want but it is impossible with single query using mysql.
But here is a php way.
function($limit,$offset){
$this->db
->select("*")
->from('tbl1');
$data["query_result"] = $this->db->get()->result_array();
$data["total_rows"] = array_slice($data["query_result"], $offset, $limit);
return $data;
}
This can be achieved with single query but involves php to get the desired result.

Generate entities with prefix in Doctrine2

I'm using doctrine2 with Zend Framework. When you build the entites need to set the prefix of the classes, for example (Model_User). Is it possible?. The command I use is
./doctrine orm:generate-entities --generate-annotations=1 ../../../application/models/
I'm new to Doctrine orm but I made this:
class TablePrefix{
protected $prefix = '';
public function __construct($prefix){
$this->prefix = '';
for($i = 0; $i < strlen($prefix); $i++){ // table prefix like in entity name
if( $prefix[$i] == '_' && $i-1 > 0 ){
$prefix[$i-1] = strtoupper($prefix[$i-1]);
}
else{
$this->prefix .= $prefix[$i];
}
}
$this->prefix[0] = strtoupper($this->prefix[0]);
}
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs){
$classMetadata = $eventArgs->getClassMetadata();
$tmp = substr($classMetadata->name, 0, strlen($this->prefix));
if($tmp == $this->prefix ){
$classMetadata->name = substr($classMetadata->name, strlen($this->prefix));
}
}
}
next when you create entity manager make this:
$tablePrefix = new TablePrefix('tbl_');
$evm = $entityManager->getEventManager();
$evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix);
on top of file add:use \Doctrine\ORM\Event\LoadClassMetadataEventArgs;
when you run cmd php vendor/bin/doctrine orm:generate-entities models model's name will be ok!
add these lines in your application.ini file.
doctrine.generate_models_options.pearStyle = true
doctrine.generate_models_options.generateTableClasses = false
doctrine.generate_models_options.generateBaseClasses = true
doctrine.generate_models_options.baseClassPrefix = "Base_"
doctrine.generate_models_options.baseClassesDirectory =
doctrine.generate_models_options.classPrefixFiles = false
doctrine.generate_models_options.classPrefix = "ModuleName_Model_"

Resources