codeigniter,filter,model,conditionals , codeigniter filter database

codeigniter filter database


Tag: codeigniter,filter,model,conditionals

i have a few checkboxes that filter my elements from a database but i don't know how to apply a filter like price with a min value and a max value, since from my view i can pass to the controller only one value of my inputs
For example: i want to apply a price filter between 1000 and 1500 to an element

        <li><input type="checkbox" name="price[]" value="1000">  <1.000</li>
        <li><input type="checkbox" name="price[]" value="1500"><a href="#">1.000 - 1.500</a></li>
        <li><input type="checkbox" name="price[]" value="2000"><a href="#">1.500 - 2.000</a></li>
        <li><input type="checkbox" name="price[]" value="3000"><a href="#">2.000 - 3.000</a></li>
        <li><input type="checkbox" name="price[]" value="4000"><a href="#">3.000 - 4.000</a></li>
        <li><input type="checkbox" name="price[]" value="5000"><a href="#">4.000 - 5.000</a></li>
        <li><input type="checkbox" name="price[]" value="5000"><a href="#">  >5.000</a></li>  


public function laptops()

    $filter = $this->input->post();

    $data['laptops_toate'] = $this->emag_model->laptops_toate_grid($filter);



    public function laptops_toate_grid($filter = null){
            ->join('brands','brands.id_brands = laptop_notebook.brand');

        $this->db->where('price <', $filter['price']);

    $query = $this->db->get()->result();

    return $query;



For just an idea of how you could do it.

The view file:

<li><input type="checkbox" name="price[]" value="<1000">  <1.000</li>
<li><input type="checkbox" name="price[]" value="1000-1500"><a href="#">1.000 - 1.500</a></li>
<li><input type="checkbox" name="price[]" value="1500-2000"><a href="#">1.500 - 2.000</a></li>
<li><input type="checkbox" name="price[]" value="2000-3000"><a href="#">2.000 - 3.000</a></li>
<li><input type="checkbox" name="price[]" value="3000-4000"><a href="#">3.000 - 4.000</a></li>
<li><input type="checkbox" name="price[]" value="4000-5000"><a href="#">4.000 - 5.000</a></li>
<li><input type="checkbox" name="price[]" value=">5000"><a href="#">  >5.000</a></li>

The controller remains the same.
The model becomes:

public function laptops_toate_grid($filter = null){
            ->join('brands','brands.id_brands = laptop_notebook.brand');

    if (isset($filter['price'])) { // make sure there is price key
        $filters = array(); // this is where we store the filters
        foreach ($filter['price'] as $price) { // iterate through prices
            if ($filter['price'][0] == '<') { // is less
                $filters[] = 'price < ' . (int)substr($price, 1);
            elseif ($filter['price'][0] == '>') { // is more
                $filters[] = 'price > ' . (int)substr($price, 1);
            else { // is between
                $expl = explode('-', $price);
                $filters[] = 'price BETWEEN ' . (int)$expl[0] . ' AND ' . (int)$expl[1];
        if ($filters) { // if there are filters, create the query
            $query = implode(' OR ', $filters);
            $query = '('. $query . ')';
            $this->db->where($query, false); // false makes sure the query is not escaped

    $query = $this->db->get()->result();

    return $query;

Note: this is just a working idea, I haven't been tested the code.


Unable to include variables in a view that was defined in another view in codeigniter

I've created a view form_variables.php that contains all the form input variables defined in a single file. So that whenever i need to create an input field, i would simply include the form_variables file and then use the form input variables defined in the form_variables.php Here's what it contains. <?php...

get information in database and insert into session codeigniter

i am new to codeigniter and using session. i am having a problem in inserting individual data in session. Model: function get_user_info() { $user_email = $this->input->post('signin-email'); $this->db->select('acct_id, acct_fname, acct_lname, acct_mname'); $this->db->where('email', $user_email); $query = $this->db->get('account'); return $query->result_array(); } Controller: public function LoginValidation(){ $this->load->library('form_validation'); $this->form_validation->set_rules('email', 'Email',...

how call another php file to Codeigniter view

how call .php outside the folder my folder structurer is I'm in cart.php my code is $tpl_file ='../mail.php';//problem is here LINE 279 $msg_tmpl = file_get_contents($tpl_file); if (!file_exists($tpl_file)) { ?> <script> alert('no'); </script> <?php } else { ?> <script> alert('yes'); </script> <?php } So my question is I want to get...

angularjs filter an array with string values as integers in contoller

I'm using AngularJS filter to filter an array of objects inside a controller. These objects all have a quality that is a string. I want to be able to filter the array from largest to smallest. But I can't get it filter on value of the integer inside the string....

jquery sortable - gives empty array in response

I am using jquery ui sortable for my codeigniter website but when i am sorting data it will give me empty array in console. please check and let me know my mistake. <script> $(document).ready( function() { $("#sortme tbody").sortable({ update : function (event, ui) { // console.log(ui); serial = $('#sortme tbody...

Array in Foreach (CodeIgniter)

I want to use array in foreach loop but failed, here is my code: foreach($this->db->get_where('mytable', array('result' => '1 or 2', 'id' => 'foo'))->result_array() I think 'result' => '1 or 2'piece has a problem but I couldn't find out how can I use array in this kind of foreach. I want...

How generate hyperlinks for news show in codeigniter

i created a news panel where we use this code for displaying news : <marquee direction="up" > <?php $query = $this->db->get('news'); foreach ($query->result() as $row) { echo $row->news; echo $row->urladdress; echo '<br/>'; } ?> </marquee> where it show correct , all data get fetched and run marquee good , but...

Connecting codeigniter to mysql and oracle in the same application

I'm using Mysql and Oracle for my CI application. I tried to connect it but I found that I cannot make a query to Oracle database. It always gave an error that the table is not exist. I already set the database.php to something like this $active_group = 'oracle'; $active_record...

Pass data to view codeigniter

Hi I need to get access to echo $Data->var_.... in my view. However, when I try to use echo I don't get data output. How can I fix it so that I get data in my view? I compressed a file with all three PHP pages here . Link *Controller...

URL Rewriting in php CodeIgniter using .htaccess

I am working on a project in which url Rewriting was done. Here is the link of the old uri But now in the new url I have changed it to what I want to do is to change the redirect all the url's whcih have search...

codeigniter session object expired availability

This might be a silly question. Once a user has been logged in, if session expires I want to redirect him to a "lockscreen" instead to a "login" page. I want to send to the lockscreen some session data (like img-src and loginname) So, here's the question. Does session object...

post serialized data through using jquery load method in codeigniter

Here is my code. <form id='user'> <label for="name">Name :</label> <input type="text" id="name" name="name"/> <label for="email">Email :</label> <input type="text" id="email" name="email"/> <input type="submit"/> </form> <div id="output"></div> jQuery: $('#user').on('submit',function(event){ event.preventDefault(); var data=$(this).serialize(); adddetails(data); }); function adddetails(data){ var url='http://localhost/projectname/index.php/users/adddat';...

Best way to serialize a JOIN SQL query to JSON

I can't find a good title for my question. I'm doing a Restful API /JSON My problem is: I have got two tables: Product: id, name Prices: id_product, price Product 1--* Prices (One product have got multiples prices) So, If I want to export the next information in JSON products:...

Cron job with CodeIgniter using wget

I am pretty new to setting up cron jobs. What I've done so far is set one up to run every 5 minutes using the following script: */5 * * * * wget -q localhost:8888/example/index.php/controller/function When I run just the wget part from the command line, it works perfectly. But...

How to modify CodeIgniter calendar to handle multiple events per day?

I am creating a calendar without jquery calendar plugin. I could retrieve the data which is in the database to the calendar. But when there are multiple data per day only one data comes to the calendar view. I want it to be like this when there is multiple data....

Disallowed key character in codeigniter

I have a view page.i have to edit a list of after submit i have an error disallowed character key.I cant find it how this error occur. view foreach($track_details->result() as $name) { ?> <form class="form-horizontal" method="post" id="income_edit" action="<?php echo base_url();?>income_list_cntrl/update_income" enctype="multipart/form-data"> <input type="text" name="track_id" value="<?php echo $track_id; ?>" >...

Unable to connect to your database server using the provided settings in Codeigniter

Actually I'm trying to configure my codeigniter live file to localhost. I have, created a database called test_bs then imported the tables Then change the base_url like $config['base_url']=http://localhost/gu_ci/'; and $config['index_page']='index.php'; in config.php And then did a change on database.php,Which contains $active_group = 'default'; $active_record = TRUE; $db['default']['hostname'] = 'localhost'; $db['default']['username']...

read more function with codeigniter

i am trying to create a readmore function in codeigniter where the readmore link will be linked to a controller which would show all the data about that particular id....i am kind of confused on how to go about it... i tried... <?php $research_detail_url = site_url()."/research/research_details"; //echo json_encode($research) if($research) {...

Group by date mysql and codeigniter

I have table like this: date_time value 2015-06-20 10:00:00 10 2015-06-20 9:00:00 6 2015-06-21 6:00:00 5 2015-06-22 11:00:00 12 2015-06-22 10:00:00 11 2015-06-23 4:00:00 20 I want to get the total value of each date Currently I have this on CodeIgniter but is not working: $this->db->group_by('date_time'); $query = $this->db->get('table_a'); Any...

Setup Codeigniter For Windows Azure

I've been trying to Setup Codeigniter 3 on the Windows Azure platform,everything seems fine for the normal setup but when i uploaded my application(Which i did via github so all the files are intact) and my session is set to autoload from config,i get the error "The resource you are...

Codeigniter Select JSON, Insert JSON

I have very simple users database: user_id, user_name, user_email My model this: class Users extends CI_Model { private $table; private $table_fields; private $table_fields_join; function __construct() { parent::__construct(); $this->table = 'users'; $this->table_fields = array( $this->table.'.user_id', $this->table.'.user_name', $this->table.'.user_email' ); $this->table_fields_join = array(); } function select(){ $this->db->select(implode(', ', array_merge($this->table_fields, $this->table_fields_join)));...

Jquery Filter Out Radio Buttons ( .not( ) )

I want to remove the radiobuttons from my multiple choice quiz so users can review their answers. I put all of the questions to be reviewed in a div called reviewQuestions var question = '#question' + zz; // zz is a variable that produces a number var someVariable = $(question).not("input[type=radio]").html();...

Severity: Warning Message: array_push() expects parameter 1 to be array, null given Filename: controllers/main.php Line Number: 676

When I run this function, I'm getting Message: array_push() expects parameter 1 to be array, null given in line number 676 Severity: Warning Message: array_push() expects parameter 1 to be array, null given Filename: controllers/main.php Line Number: 676 function get_order_details() { $query1="SELECT * FROM order_main "; $o_main=$this->main_model->query_return($query1); $query="SELECT * FROM...

unable to get form_validation->set_rules and form_validation->set_message error

I have autoload helper form and library form-validation in autoload.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Login extends CI_Controller { var $data; public function __construct(){ parent::__construct(); $this->data=array('page'=>'login_view','title'=>'login'); $this->load->model("Login_model"); } public function index() { //get the posted values $data=$this->data; $this->load->view('template',$data); } public function checklogin(){ //form validation $data=$this->data;...

Creating a list of items with different tags + filter

I have prepared an example what I would like to produce: link. I have already looked for something and I have found the way to create a filter but just for one value... In my case I need more values all together combined. So that if I wanted a flat...

How to insert radio button value into the database?

I want to insert selected radio button value into the database. just "yes" or "no". if anyone can give me an idea it would be a great help. I am using codeigniter framework. Thanks in advance. Model function add_reservation($reservation_model) { return $this->db->insert('reservations', $reservation_model); } Controller function add_reservation() { $reservation_model =...

AngularJS Filter two select inputs with values less than or equal to value

I would like to setup two select inputs so that the combined value of either select input should be less than or equal to a specific value. Newbie to the AngularJS world so I may have overlooked something. I assume a filter but it might be ng-change that I should...

How do I do to count rows in a sheets with filters? With a suppress lines

I have a sheet with lots of columns, but when I filter and use count = Application.WorksheetFunction.CountA(Range("A:A")) It returns all the rows non Empty. Not only the rows I filtered....

When I click to the next page on pagination,it goes to 404 error in codeigniter

In my News.phpcontroller,i'm having the below code: public function index() { $data['title'] = 'Database Details'; $config = array(); $config['base_url'] = base_url("news/index"); $config['total_rows'] = $this->news_model->record_count(); $config['per_page'] = 5; $config['uri_segment'] = 3; //$config['use_page_numbers'] = TRUE; // $config['page_query_string'] = TRUE; $choice = $config["total_rows"] / $config["per_page"]; $config["num_links"] = round($choice); $this->pagination->initialize($config); $page =...

2 join conditions codeigniter giving error

I have 2 tables - for orders and for documents for these orders. I want to show all orders from first table and if there are documents for these orders, to show date of documents(I take date from table documents). I'm trying to make 2 join conditions because in table...

Setting session variable after destroying previous session

Why isn't the session variable value available on the second page load when I click the "Fake Login" link? class Fake_login extends CI_Controller { function __construct() { parent::__construct(); echo $this->session->userdata('session_id') . '<br>'; // First Page Load: ee3c7c5da6e465605cd57ad699aacdb3 // Second Page Load: c82adf312f123d56e3b7b6ab5ec6cafa echo $this->session->userdata('variable') . '<br>'; // First Page Load:...

What would cause CI to falsely return null values?

I'm running this in CI, and $query->result_array() is returning null values, however, when I use $this->db->last_query(), and print out the query, then run it in a MySQL client (Sequel Pro), I get values back as I would expect. What would cause this to return NULL when doing it through CI?...

Mysql query not working if i add parameter dynamically in CI model

I have an sql select query with where. If I put a static value, it works fine. But if I use a parameter value like $name, it doesn't work. Here's my sample code: I'm using codeigniter, this query written in model. working query: (It returns a correct value) function getid($email){...

How to subset by distinct rows in a data frame or matrix?

Suppose I had the following matrix: matrix(c(1,1,2,1,2,3,2,1,3,2,2,1),ncol=3) Result: [,1] [,2] [,3] [1,] 1 2 3 [2,] 1 3 2 [3,] 2 2 2 [4,] 1 1 1 How can I filter/subset this matrix by whether or not each row has duplicate values? For example, in this case, I would only...

Get array output of one function in another function php

I have below controller function of codeigniter, public function add_attachments($openid) { $config = array( 'upload_path' => './uploads/attachments/', 'allowed_types' => 'gif|jpg|png|jpeg|doc|pdf', 'max_size' => '1024000000', 'multi' => 'all' ); $this->load->library('upload', $config); if ( ! $this->upload->do_upload()) { $error = array('error' => $this->upload->display_errors()); } else { $data = $this->upload->data(); } $new_array = array_column ($data,...

Helper Not Detcteing Subfolder Paths Codeigniter

On my helper function if controller is in parent directory I can load controllers from subfolders load_controller('subfolder/class'); Problem If I have a controller that is in a subfolder and want to use this load_controller('subfolder/class'); I cannot pick it up other controllers if I call them from a controller that is...

Add custom error messages to CI validation_errors()

There's a way to add custom error messages to CodeIgniter validation_errors();? Example, if I wanted a field with a 123456 value, and the user inputs 12345 I'd want to set a message to say: The number 6 is required! And any other custom rules I may want to add. Like...

Excel VBA - ShowAllData fail - Need to know if there is a filter

I have automated a proper record input into the table that I use as a database, and when the table is filtered the input don't work. So I have code this to unfilter DataBase before every record input. Public Sub UnFilter_DB() Dim ActiveS As String, CurrScreenUpdate As Boolean CurrScreenUpdate =...

using if else with codeigniter return value

I am using codeigniter framework for one of my inventory management systems. I prefer using php due to its variable functionality which makes things easier. So I am trying to get the username from session and then check the database for the level of the user and accordingly he should...

REST API with token based authentication

I want to develop a web site with AngularJS. On the backend side I will use Codeigniter REST framework. I have some security issues and I don't want to start developing without fixing them on my mind. I don't want to use something like api key because it will be...

How to add support gd library to server

I have applied following code. But didn't find any solution. How I can add support gd library to server. public function addreqdoctor() { if($_FILES['userfile']['name']){ $ext = end(explode(".", $_FILES['userfile']['name'])); $new_name = time()."_".rand(1,10000).'.'.$ext; $basic['picture'] = $new_name; $config['upload_path'] = './doctors/'; $config['allowed_types'] = 'gif|jpg|png'; $config['file_name'] = $new_name; $this->load->library('upload', $config); if ( ! $this->upload->do_upload()) {...

Excel VBA range after filtering xlCellTypeVisible

What I want to accomplish: Open a workbook from a specific address, Filter the first column for value equal to 36 or 541 (I got this first part working), then check column 3 to see if a value of 2 exists and if it exists then filter out everything except...

Unable to pass vairables through helper function Codeigniter

On my Codeigniter Custom helper I would like to be able to pass data through my load_controller function $params But I cannot pass any data through load_controller('controller', 'function', $setting); Custom Helper <?php if (!function_exists('load_controller')) { function load_controller($controller, $method = 'index', $params = '') { require_once(APPPATH . 'controllers/' . $controller ....

how to multiply two column names using codeigniter validation rule

I have three columns.The product of two columns get into third column name income_amount using codeigniter validation rule.the first column is crop_quantity and the second is per_rate controller $this->form_validation->set_rules('crop_quantity', 'Crop Quantity', 'required|numeric'); $this->form_validation->set_rules('per_rate', 'Per Rate', 'required|numeric|callback_get_product'); $this->form_validation->set_rules('income_amount', 'Income Amount', 'required|numeric');...

My website Images not indexed by Google, Yahoo and Bing [closed]

I'm using codeigniter framework. why Search Engine's not indexed my website images ? My website has been made since 2013. My website is : It likes groupon website(Offering daily deals at restaurants, retailers and service providers.). An image url : What should I do to tell search engines...

Associative array turned into where OR clause in Codeigniter

using CI I'm trying to set up query with three parameters: user_id, content_type and content_id in which content_id is array of IDs. So I need to get up with something like this: SELECT name FROM content WHERE user_id = 2 AND content_type = file AND (content_id = 4 OR content_id...

Codeigniter Form Validation Rule for match (password)

I am trying to write Form validation rules in my Controller to submit Change Password form in which I am checking the old password too. I am getting the old password(current) from db and placing it in a hidden input field. My Rules are simple and are given below $config=array(...

How to call this function for every controller in codeigniter

My situation is that, I have 20 controllers in my website, where I have a function like this. $this->lang->load("main", $this->session->userdata("lang_code")); How can I load this function in all the 20 controllers without adding it individually to the __constructor of every controller?...

Filter array of objects with another array of objects

This question is similar to this one Jquery filter array of object with loop but this time I need to do the filter with an array of objects. Exemple: I have an array of objects like this: myArray = [ { userid: "100", projectid: "10", rowid: "0" }, { userid:...

how to insert one value into db

in my view i have one dropdown menu and one my dropdown list contain 3 values daily salary,weekly salary and monthly salary..And the text field for amount.. in my db contain 3 columns for daily,weekly and monthly if i select a value in my dropdown then enter an amount...