how to get sum of database column in codeigniter? - php

Friends I'm Unable to get open positions Sum. here is my code. I am getting 1(one) instead of total sum. Help me to solve this issue.
Controller:
function index(){
$userId = $this->phpsession->get("userId");
$userType = $this->phpsession->get('userType');
$date = date("Y-m-d");
if(!$userId && !$this->phpsession->get("userType")){
redirect(base_url().'user');
}
$config['base_url'] = base_url().'requirement/index';
$config['total_rows'] = $this->requirement_model->GetRequirement(array("count"=>true));
$config['per_page'] = 5;
$config['cur_tag_open'] = '<a>';
$config['cur_tag_close'] = '</a>';
$this->pagination->initialize($config);
$options['offset'] = $this->uri->segment(3);
$options['limit'] = $config['per_page'];
$options['join']=true;
$data['clients'] = $this->client_model->ajaxclient();
$data['requirements'] = array(""=>"Choose requirement");
$data['requirement'] = $this->requirement_model->GetRequirement($options);
$data['links'] = $this->pagination->create_links();
$data['totalactive']=$this->requirement_model->GetRequirement(array("find"=>true));
$data['totalrequirement']=$this->requirement_model->GetRequirement(array("totalreq"=>true));
$data['openpositions']=$this->requirement_model->GetRequirement(array("openpos"=>true));
//print_R($data['openpositions']);exit;
//echo "<pre>"; print_R($this->db->last_query()); exit;
$data['page_title'] = "Requirement Details";
$this->layout->view("requirement/index",$data);
}
This is my model function
Model:
function GetRequirement($options = array()){
if(isset($options['requirementId']))
$this->db->where('requirementId',$options['requirementId']);
if(isset($options['clientName']))
$this->db->where('clientName',$options['clientName']);
if(isset($options['limit']) && isset($options['offset']))
$this->db->limit($options['limit'], $options['offset']);
else if(isset($options['limit']))
$this->db->limit($options['limit']);
$this->db->order_by("activateddate", "DESC");
if(isset($options['join'])){
$this->db->select('r.*,c.clientName as cName');
$this->db->from('requirement as r');
$this->db->join('clients as c','c.clientId=r.clientName');
$query=$this->db->get();
if(#$options['requirementId']) return $query->row(0);
return $query->result();
}
if(isset($options['find'])){
$this->db->select('distinct(clientName)');
$this->db->from('requirement');
$this->db->where('(clientName) and (noofpositions > 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
if(isset($options['totalreq'])){
$this->db->select('requirementName');
$this->db->from('requirement');
$this->db->where('(noofpositions > 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
if(isset($options['openpos'])){
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
$query = $this->db->get('requirement');
if(isset($options['count'])) return $query->num_rows();
if(#$options['requirementId']) return $query->row(0);
return $query->result();
}
This is my View page
View:
<div class="inner">
<h3><?php echo $openpositions; ?></h3>
<p>Total Positions Opened</p>
</div>

You are using sum which is an aggregate function and with out group by it will take whole table as one group in if(isset($options['openpos'])){ ... } part of code of your model your are returning num_rows() which returns the no. of rows so in your case there will be one row with the value of sum therefore you are getting result as 1 change your
if (isset($options['openpos'])) {
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$query = $this->db->get();
return $query->row()->openpos;
}

I think the mysql statement has an error.
Change the following line:
$this->db->where('(closedPos = 0) ');
To
$this->db->where('closedPos', 0);
remove the following line: (this will count all rows and return the value, which you do not want)
$this->db->countall();
If this does not solve your problem you could try outputting the mysql statement by adding exit($this->db->last_query()); to try and find the problem, like this:
if(isset($options['openpos'])){
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$this->db->count_all();
$query=$this->db->get();
// output last query
exit($this->db->last_query());
return $query->num_rows();
}

Related

pagination more than 1 table

i want to make pagination on ci from other web reference, but average of them use only 1 table
does anyone know how to input more than 1 table on this condition
public function data($number,$offset){
return $query = $this->db->get('client',$number,$offset)->result();
}
i have try to input like this
public function data($number,$offset){
return $query = $this->db->get('client,advertisement,size',$number,$offset)->result();
}
but the result is not my expected
the NAMA is looping, the IKLAN too but the SIZE is not
i take the refences from here
I use this:
public function fetch_countries($limit, $start) {
$this->db->limit($limit, $start);
$this->db->join('client', 'advertisement.id_client= client.id_client','inner');
$this->db->join('size', 'advertisement.id_size= size.id_size','inner');
$query = $this->db->get("advertisement");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}

Codeigniter Select and Count MySQL Records

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;
}

Json returns a duplicate value using codeigniter

I am trying to fetch a data for each chkey with a related value as a group in codeigniter. When there are a 2 or more chkey then code is work properly.
But when there is a only 1 chkey then it shows value of that chkey but it is shows extra chkey:null,value:null in json.
Related json for chkey is 1 is as follows'
[{"unit_id":"8","CHGRAPHUpdatetime":{"time":"2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00"},"channelGraph":[{"chkey":"ch1","list":"2,-30,12,20"},{"chkey":"null","list":"null"}]}]
Expected is,
[{"unit_id":"8","CHGRAPHUpdatetime":{"time":"2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00"},"channelGraph":[{"chkey":"ch1","list":"2,-30,12,20"}]}]
Could you please help me to resolve this issue.
model code-
public function chGraph($unitid){
$this->db->select("unit_id");
$this->db->from("device_unit");
$this->db->where('unit_id', $unitid);
$query = $this->db->get();
$unit = $query->result_array();
$j = 0;
foreach($unit as $row) {
$unit[$j]['CHGRAPHUpdatetime'] = $this->UnitCHGRAPHUpdatetime($row['unit_id']);
$unit[$j++]['channelGraph'] = $this->UnitCHGRAPHDetails1($row['unit_id']);
}
return $unit;
}
public function UnitCHGRAPHDetails1($unit_id)
{
$this->db->select('distinct(chkey)','chvalue');
$this->db->from('channel_info');
$query = $this->db->get();
$channelgraphData = $query->result_array();
$m = 0;
foreach($channelgraphData as $row) {
$chvalueQuery = 'SELECT chkey, GROUP_CONCAT(chvalue)as list FROM channel_info where chkey= "'. $row['chkey'] .'" and unit_id='. $unit_id .'';
$response = $this->db->query($chvalueQuery)->row();
$channelgraphData[$m++] = $response;
}
return $channelgraphData;
}
controller code-
public function chGraph()
{
$unitid = $this->uri->segment('3');
$GraphDetails = $this->device_model->chGraph($unitid);
echo json_encode($GraphDetails);
}
You could add a GROUP BY at the end of the statement to eliminate the null results :
$chvalueQuery = 'SELECT chkey, GROUP_CONCAT(chvalue)as list FROM channel_info where chkey= "'. $row['chkey'] .'" and unit_id='. $unit_id .' GROUP BY chkey';

Codeigniter- get query results

I want to get all query results where I get the id's from another query. I get all relevant id's from both table but i can show only one result in my view. Where is my folt, and how can I fix this?
my Controller:
$results = $this->my_model->hd($query_array ,$limit, $offset);
$data['r']= $results ['rows'];
$data['num_results']= $results ['num_rows'];
$id_str = '';
foreach($results['rows'] as $row){
$id_str .= $row->id . ',';
}
$id_str = rtrim($id_str, '');
$doff = $this->my_model->off($id_str);
$data['o']= $doff ['rows'];
My Model:
function hd($query_array,$limit, $offset){
//result query
$q = $this->db->select('*')
->from('a')
->limit($limit, $offset);
if (strlen($query_array['cy'])){
$q->like('cy', $query_array['cy']);
}
if (strlen($query_array['cat'])){
$q->where('cat', $query_array['cat']);
}
if (strlen($query_array['rat'])){
$q->where('rat', $query_array['rat']);
}
$ret['rows'] = $q->get()->result();
$q = $this->db->select('COUNT(*) as count', FALSE)
->from('r');
if (strlen($query_array['cy'])){
$q->like('cy', $query_array['cy']);
}
if (strlen($query_array['cat'])){
$q->where('cat', $query_array['cat']);
}
if (strlen($query_array['rat'])){
$q->where('rat', $query_array['rat']);
}
$tmp = $q->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}
function off($id_str){
$off_a = $this->db->select('*')
->from('off')
->where('r_id', $id_str);
$ret['rows'] = $off_a->get()->result();
return $ret;
}
I show in my view the result in a foreach loop. I tried to fix this problem since three days by my self and google, but no luck.

How to create pagination links when combining data from two different queries

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

Categories