I am new in PHP and learning Codeigniter. I have an issue to put where condition with my search query. My controller is like below
public function index(){
$data = array();
// Get messages from the session
if($this->session->userdata('success_msg')){
$data['success_msg'] = $this->session->userdata('success_msg');
$this->session->unset_userdata('success_msg');
}
if($this->session->userdata('error_msg')){
$data['error_msg'] = $this->session->userdata('error_msg');
$this->session->unset_userdata('error_msg');
}
// If search request submitted
if($this->input->post('submitSearch')){
$inputKeywords = $this->input->post('searchKeyword');
$searchKeyword = strip_tags($inputKeywords);
if(!empty($searchKeyword)){
$this->session->set_userdata('searchKeyword',$searchKeyword);
}else{
$this->session->unset_userdata('searchKeyword');
}
}elseif($this->input->post('submitSearchReset')){
$this->session->unset_userdata('searchKeyword');
}
$data['searchKeyword'] = $this->session->userdata('searchKeyword');
// Get rows count
$conditions['searchKeyword'] = $data['searchKeyword'];
$conditions['returnType'] = 'count';
$rowsCount = $this->member->getRows($conditions);
// Pagination config
$config['base_url'] = base_url().'members/index/';
$config['uri_segment'] = 3;
$config['total_rows'] = $rowsCount;
$config['per_page'] = $this->perPage;
// Initialize pagination library
$this->pagination->initialize($config);
// Define offset
$page = $this->uri->segment(3);
$offset = !$page?0:$page;
// Get rows
$conditions['returnType'] = '';
$conditions['start'] = $offset;
$conditions['limit'] = $this->perPage;
$data['members'] = $this->member->getRows($conditions);
$data['title'] = 'Members List';
// Load the list page view
//$this->load->view('templates/header', $data);
$this->load->view('members/index', $data);
//$this->load->view('templates/footer');
}
and my model is like below
function getRows($params = array()){
$this->db->select('*');
$this->db->from($this->table);
//$where = "is_verified = 1";
//$this->db->where($where);
if(array_key_exists("conditions", $params)){
foreach($params['conditions'] as $key => $val){
$this->db->where($key, $val);
}
}
if(!empty($params['searchKeyword'])){
$search = $params['searchKeyword'];
$likeArr = array('fname' => $search, 'lname' => $search, 'gran_id' => $search);
$this->db->or_like($likeArr);
}
if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
$result = $this->db->count_all_results();
}else{
if(array_key_exists("user_id", $params)){
$this->db->where('user_id', $params['user_id']);
$query = $this->db->get();
$result = $query->row_array();
}else{
$this->db->order_by('fname', 'asc');
if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit'],$params['start']);
}elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit']);
}
//$query = $this->db->get();
$query = $this->db->where('is_verified', '1')->get();
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
}
}
// Return fetched data
return $result;
}
I want to fetch only records where
is_verified = 1
and so I have put it with my query and its working fine without search query. If I search its showing record even if_verified have another value. I am not getting idea which another place I should put this where condition so when I search, it can show only required records.
Thanks!
This will happen when using or_like in Codeigniter you should use group_start and group_end function to separate your search with where condition
if(!empty($params['searchKeyword'])){
$search = $params['searchKeyword'];
$likeArr = array('fname' => $search, 'lname' => $search, 'gran_id' => $search);
$this->db->group_start(); // this will make brackets for your search query
$this->db->or_like($likeArr);
$this->db->group_end();
}
You are not filtering the query when a search is performed you're only doing it outside of a search.
Try: Find this block
if(!empty($params['searchKeyword'])){
$search = $params['searchKeyword'];
$likeArr = array('fname' => $search,'lname' => $search, 'gran_id' => $search);
$query = $this->db->where('is_verified', '1');
$this->db->or_like($likeArr);
}
Related
Using Codeigniter 3, I would like to display all the records from a table in a MySQL database. I'd also like to include the number of records selected.
For example;
Showing x number of records;
record 1
record 2
record 3
etc
Currently I have the following (which works);
// select all records
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
// count all records
public function countRecords() {
$this->db->select('count(*) as count');
$this->db->from('records');
$query = $this->db->get();
return $query->row();
}
My question is do I need two separate queries in order to achieve this (select and count)?
Is there a more efficient way of achieving what I want?
You can do something like this :
public function selectRecords()
{
$query = $this->db->get('records');
if ($query->num_rows() > 0 )
{
$records = $query->result_array();
$data['count'] = count($records);
$data['all_records'] = $records;
return $data;
}
}
Pass it to the view from your controller :
$data = $this->model_name->selectRecords();
/*print_r($data) to see the output*/
$this->load->view('your_view',$data);
In view :
<?php echo $count .' number of records';?>
you can do only:
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
and
$records = $this->selectRecords();
$count = count($records);
In The first function itself you can get the count using $query->num_rows() function
public function selectRecords() {
$return = array();
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
$return['count'] = $query->num_rows();
$return['records'] = $query->result_array();
return $return;
}
try this
it will help you to provide pagination for records
public function selectRecords($params = array(), $count = false) {
$offset = isset($params['offset']) ? $params['offset'] : '';
$limit = isset($params['limit']) ? $params['limit'] : '';
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
if ($count) {
return $this->db->get()->num_rows();
}
if (empty($offset) && !empty($limit)) {
$this->db->limit($limit);
}
if (!empty($offset) && !empty($limit)) {
$this->db->limit($limit, $offset);
}
$result = $this->db->get()->result();
return $result;
}
i have searching routes with get and post. First time users select search filters from home page then it submit it hit on index controller search with form data and return correct results with pagination when i click on pages it does not show any thing.
Route::post('search', 'SearchController#index');
Route::get('search', 'SearchController#index');
And i have index controller for search with post first time and with session like this.
public function index(Request $request)
{
if( Request::get('select_menu') !='' ){
$conditions = array();
$conditions['city'] = Request::get('city');
$conditions['area'] = Request::get('area');
$conditions['purpose'] = Request::get('status');
$results = Property::where($conditions)->whereBetween('price', array(1000, 10000))->paginate(6);
Session::set('formDataSession', $conditions);
}
elseif(Session::has('formDataSession')){
$getSession = Session::get('formDataSession');
$conditions = array();
$conditions['city'] = $getSession['city'];
$conditions['area'] = $getSession['area'];
$conditions['purpose'] = $getSession['purpose'];
$results = Property::where($conditions)->whereBetween('price', array(1000, 10000))->paginate(6);
}
return view('search', array('page' => 'search','results'=>$results));
}
public function index(Request $request)
{
$results = Property::whereBetween('price', [1000, 10000]);
$conditions = [];
if ($request->has('select_menu')) {
$conditions['city'] = $request->city;
$conditions['area'] = $request->area;
$conditions['purpose'] = $request->status;
session(['formDataSession' => $conditions]);
}
$getSession = session('formDataSession');
$conditions['city'] = $getSession['city'];
$conditions['area'] = $getSession['area'];
$conditions['purpose'] = $getSession['purpose'];
$results = $results->where($conditions)->paginate(6);
return view('search', ['page' => 'search', 'results' => $results]);
}
I have the following function, the params are "asc,PV1"
public function get_products($order, $sku){
if(is_array($result) && $result['active']){
$id_emp = $result['id_emp'];
$mts = 'module_tienda_status';
$mtc = 'module_tienda_categories';
$mtp = 'module_tienda_productos';
$mtpt = 'module_tienda_product_type';
$mtpa = 'module_tienda_product_attribute';
$mta = 'module_tienda_attributes';
$mtao = 'module_tienda_attribute_option';
$mtpv = 'module_tienda_product_variation';
$mtpvo = 'module_tienda_product_variation_options';
$get = array(
$mtp.'.id',
$mtp.'.name',
$mtp.'.sku',
$mtp.'.desc_short',
$mtp.'.desc_long',
$mtp.'.id_category',
$mtp.'.price',
$mtp.'.id_status',
$mtp.'.inventory',
$mtp.'.imgs',
$mtp.'.qty',
$mtp.'.featured',
$mtc.'.name as cat_name',
$mtpt.'.id as type_id',
$mtpa.'.id_attribute',
$mtpa.'.id_option',
$mta.'.name as attr_name',
$mtao.'.option as opt_name',
$mtpv.'.inventory as var_inv',
$mtpv.'.qty as var_qty',
$mtpv.'.price as var_price',
$mtpvo.'.id_product_variation as var_id',
$mtpvo.'.id_attribute as var_attr',
$mtpvo.'.id_option as var_opt'
);
$this->db->select($get);
$this->db->from($mts);
$this->db->join($mtp, $mtp.'.id_status = '.$mts.'.id');
$this->db->join($mtc, $mtp.'.id_category = '.$mtc.'.id', 'left');
$this->db->join($mtpt, $mtp.'.id_product_type = '.$mtpt.'.id');
$this->db->join($mtpa, $mtpa.'.id_product = '.$mtp.'.id', 'left');
$this->db->join($mta, $mta.'.id = '.$mtpa.'.id_attribute', 'left');
$this->db->join($mtao, $mtao.'.id = '.$mtpa.'.id_option', 'left');
$this->db->join($mtpv, $mtp.'.id = '.$mtpv.'.id_product', 'left');
$this->db->join($mtpvo, $mtpv.'.id = '.$mtpvo.'.id_product_variation', 'left');
$this->db->where($mtp.'.id_emp', $id_emp);
if($sku != 'null'){
$this->db->where($mtp.'.sku', $sku);
}
if(!is_null($order)){
$this->db->order_by('module_tienda_productos.created', $order);
}
$query = $this->db->get()->result();
}else{
return $result;
}
}
the result is an array with 49 rows of the same product, the difference is that there are different attributes and variations, here is the example https://pastebin.com/3X4w6wEi
What i want is 1 single result with an array of attributes and 1 array of variations something like this (is a json, please decode it)
[{'id':'343','name':'Producto variable 1','sku':'PV1','desc_short':'<p><br></p>','desc_long':'<p><br></p>','id_category':null,'price':null,'id_status':'1','inventory':'0','imgs':null,'qty':'0','featured':'0','cat_name':null,'type_id':'2','attributes':[{'id_attribute':'49','attr_name':'Colors','opts':{'107':'Amarillo','110':'Celeste','121':'Rojo','122':'Azul'}},{'id_attribute':'57','attr_name':'Size','opts':{'112':'xs','113':'s','114':'n','116':'xl'}}],'variations':[{'var_id':'42','var_inv':'0','var_qty':'0','var_price':'0.00','opts':[{'id_attribute':'49','attr_name':'Colors','opts':{'107':'Amarillo','110':'Celeste','121':'Rojo','122':'Azul'}},{'id_attribute':'57','attr_name':'Size','opts':{'112':'xs'}}]}]}]
I have a controller with a method that looks something like this:
public function browsecategory($category_id)
{
//find any subcategories for this category
$this->load->model('category/category_model');
$this->load->model('category/product_category_model');
$records['categories'] = $this->category_model->find_all_by('parent_id', $category_id);
//add some product data too.
$records['products'] = $this->product_category_model->find_all_by('category_id', $category_id);
Template::set('records', $records);
Template::render();
}//end browsecategory
All the examples I've seen for the codeigniter pagination "stuff" is using one query.
I need to combine two data sets and serve on one view.
Any suggestions?
EDIT 1
I've tried to follow MDeSilva's suggestion below. And although the pagination object is correctly calculating the number of links to create, all items appear on all pages.
Here's the code in the model that gets the data:
public function get_categories_and_products($limit=12, $offset=0, $category_id=null)
{
print '<BR>the function got the following offeset:'.$offset;
$query = "(SELECT cat.category_id, cat.title, cat.image_thumb, cat.deleted, cat.display_weight ";
$query = $query."FROM bf_categories cat ";
$query = $query."WHERE cat.parent_id=".$category_id;
$query = $query." AND cat.category_id <>".$category_id;
$query = $query.") UNION (";
$query = $query."SELECT p.product_id, p.name, p.image_thumb, p.deleted , p.display_weight";
$query = $query." FROM bf_product p ";
$query = $query."Inner join bf_product_category cp ";
$query = $query."on p.product_id=cp.product_id ";
$query = $query."Where cp.category_id=".$category_id.")";
$this->db->limit($limit, $offset);
$catsandprods= $this->db->query($query);
return $catsandprods->result() ;
}
And here's the code in the controller:
public function browsecategory($category_id, $offset=0)
{
$this->load->library('pagination');
$total = $this->product_model->get_cats_prods_count($category_id);
$config['base_url'] = site_url('/product/browsecategory/'.$category_id);
$config['uri_segment'] = 4;
$config['total_rows'] = $total;
$config['per_page'] = 5;
$config['num_links'] = 10;
$this->pagination->initialize($config);
$offset = ($this->uri->segment($config['uri_segment'])) ? $this->uri->segment($config['uri_segment']) : 0;
print $offset;
//Call the model function here to get the result,
$records= $this->product_model->get_categories_and_products(5,$offset,$category_id);
//add to breadcrumb trail
$this->build_bread_crumb_trail($category_id);
$breadcrumbs = $this->breadcrumbs->expand_to_hyperlinks();
Template::set('currentcategory',$category_id);
Template::set('breadcrumbs', $breadcrumbs);
Template::set('records', $records);
Template::render();
}
I've debugged and I can see that the line of code "$this->db->limit($limit, $offset);" in the model is not working. It always returns the full record set...
Can you tell me what I'm missing?
Thanks.
This is the way to generate pagination links in CI, for your requirement have a query with a join,
public function index($offset = 0) {
$language_id = 1;
$artwork_id = null;
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$artwork_id = $this->input->post('serach_artwork_id', TRUE) ? $this->input->post('serach_artwork_id', TRUE) : null;
$data['artwork_id'] = $artwork_id;
}
$this->load->library('pagination');
$limit = 10;
$total = $this->Artwork_model->get_artwork_count($language_id, $artwork_id);
$config['base_url'] = base_url().'artwork/index/';
$config['total_rows'] = $total;
$config['per_page'] = $limit;
$config['uri_segment'] = 3;
$config['first_link'] = '<< First';
$config['last_link'] = 'Last >>';
$config['next_link'] = 'Next ' . '>';
$config['prev_link'] = '<' . ' Previous';
$config['num_tag_open'] = '<span class="number">';
$config['num_tag_close'] = '</span>';
$config['cur_tag_open'] = '<span class="current"><a href="#">';
$config['cur_tag_close'] = '</a></span>';
$this->pagination->initialize($config);
//Call the model function here to get the result,
$data['artworks'] = $this->Artwork_model->get_artworks($language_id, $limit, $offset, $artwork_id);
$this->template->write('title', 'Artwork : Manage Artwork');
$this->template->write_view('content', 'artwork/index', $data);
$this->template->render();
}
Here is an example for query with multiple joins in the model
public function get_artworks($language_id = 1, $limit = 10, $offset = 0, $arwork_id = null)
{
$this->db->select('a.id, a.price, a.is_shop, at.title,at.status,at.date_added,ats.name as artist_name');
$this->db->from('artworks a');
$this->db->join('artwork_translations at', 'a.id = at.artwork_id');
$this->db->join('artists ats', 'a.artist_id = ats.id');
$this->db->where('at.language_id', $language_id);
if(!is_null($arwork_id) && !empty($arwork_id) && $arwork_id != 'all')
{
$this->db->where('a.id =', $arwork_id);
}
$this->db->order_by('a.id DESC');
$this->db->limit($limit, $offset);
$artworks = $this->db->get();
return $artworks->result();
}
In the View
<?= $this->pagination->create_links(); ?>
The pagination class doesn't care about the how the data source is constructed, just so you hand it the data result object it wants. So you would just pass limits & offsets into your data queries, or else pull all your data and slice it up afterwards.
However, I don't really understand how you are thinking to combine these different bits of data into a single result to display - are you trying to display all categories, then paginate the products? If so, you are set up incorrectly
Simply use PHP function array_merge
<?php $beginning = 'foo'; $end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
$this->load->view('view.php', $result);
?>
and extract according to keys for array used.
It is really simple & working
I am developing a CMS which works on template page system in a different approach.
I have this object:
$structure = new stdClass;
$structure->homepage->news->method = 'get_articles_by_page_name';
$structure->homepage->news->lang_key = translate('home_news');
$structure->homepage->news->lang = $lang;
$structure->homepage->news->add_media = true;
$structure->homepage->news->media_type = 'ibs';
$structure->homepage->news->limit = '5';
$structure->homepage->news->order_by = 'a.logical_date';
$structure->homepage->news->asc_des = 'desc';
$structure->homepage->news->result_type = 'result';
This helps to get contents as following:
foreach ($structure as $page_template => $page_contents)
{
// Call Customized Content for Homepage
if($this->data['page_data']->page_view == $page_template) // homepage comes ok.
{
foreach ($page_contents as $view_var_name => $page_cdata)
{
$method = $page_cdata->method; // method names comes
$page_cdata = substr(implode(",",(array) $page_cdata),(strlen($method)+1)) . '\'';
//Returns as expected:
//**'Haberler','tr','1','ibs','5','a.logical_date','desc','result'**
$this->data[$view_var_name] = $this->publish->$method($page_cdata);
vdebug($page_cdata);
}
}
}
It suppose to call them model function of:
function get_articles_by_page_name( $lang_key='',$lang='en',$add_media=true,
media_type='ibs',$limit='0',$order_by='a.logical_date',$asc_desc='desc',$result_type='result')
However, there is a problem with. When I return to last worked query it says:
SELECT * FROM (`page`) JOIN `page_lang` ON `page`.`id_page` = `page_lang`.`id_page` WHERE `page_lang`.`title` = '\'News\',\'tr\',\'1\',\'ibs\',\'5\',\'a.logical_date\',\'desc\',\'result\''
It souldn't be like this. every thing between commas are parameters of the method function. What cause this, any idea?
Content of get_articles_by_page_name:
function get_articles_by_page_name ($lang_key='',$lang='tr',$add_media=true,$media_type='ibs',$limit='0',$order_by='a.logical_date',$asc_desc='desc',$result_type='result')
{
// Define variables
$id_page = '';
$result = '';
// Get Page Data
$page_name = $lang_key;
$get_page = $this->vayes->getJoined('page','page_lang','id_page','','',array('page_lang.title'=>$page_name),'row');
if($get_page)
{
$id_page = $get_page->id_page;
$result = $this->publish->get_articles($lang,$id_page,null,false,'',$order_by,$asc_desc,$limit,'result');
}
else
{
$result = array('No id_page specified');
}
return $result;
}
Content of get_articles:
function get_articles($lang='tr',$id_page,$id_article=null,$incl_media=true,$media_type='',$order_by='a.logical_date',$asc_desc='desc',$limit='0',$result_type='result')
{
$this->db->select('*');
$this->db->from('article a');
$this->db->join('article_lang b','b.id_article=a.id_article','left outer');
if($incl_media) {
$this->db->join('article_media c','c.id_article=b.id_article','left outer');
$this->db->join('media d','d.id_media=c.id_media','left outer');
}
if($id_article == null) { $this->db->where('a.id_page',$id_page); }
else /*------------->*/ { $this->db->where('a.id_article',$id_article); }
$this->db->where('b.lang',$lang);
$this->db->where('b.online',1);
if(($incl_media == true) AND $media_type != '' ) $this->db->where('c.usage',$media_type);
// Order Results
$this->db->order_by($order_by,$asc_desc);
// Limit Results
if ($limit) $this->db->limit($limit);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->$result_type();
$query->free_result();
return $result;
}
return false;
}
try stripslashes()
Attempting to use stripslashes on an array in 5.2.17 returns the string "Array", but in 5.3.6 it returns NULL. So using stripslashes() on an array you will need to do it recursively;
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
// Output
print_r($array);