Codeigniter Count Query - php

How do I structure the below query in Codeigniter. I can't seem to figure it out.
This is the function in my model:
public function update_daily_inventory(){
foreach ($this->parseInventoryHtml() as $item)
{
$_item = $this->db->query('SELECT COUNT(*) as `count` FROM product WHERE product_code = "'.$item['sku'].'"');
}
return $_item;
}
I want to use an array key as the where variable. Apologize if this is simple I am new to coding. This keeps returning 0.

$this->db->where('product_code', $item['sku']);
$this->db->select('COUNT(*) as `count`');
$_item = $this->db->get('product')->row()->count;

There is no need to set alias for count.here is simple query to count number of rows found in result.
$this->db->where('product_code', $item['sku']);
$this->db->select('*');
$_item = $this->db->get('product')->num_rows();

You can use below code to structure your query.
$this->db->select('*');
$this->db->where('product_code', $item['sku']);
$_item = $this->db->count_all_results('product');
Hope this helps.

Related

Cannot get data after joining from multiple tables in Codeigniter

I want to get data from two tables, the second table is for rating so i want to get rating of products simultaneosly. Below code is not working for me if i change
$this->db->select('dg_products.',', AVG(dg_rating.rating) As
averageRating');
to
$this->db->select('*');
then it is working.
Please help to sort out my issue.
public function get_rating()
{
$this->db->select('dg_products.*','*, AVG(`dg_rating.rating`) As averageRating');
$this->db->from('dg_products');
$this->db->join('dg_rating', 'dg_products.id = dg_rating.product_id','left');
$this->db->where('dg_products.is_featured_prod','1');
$this->db->group_by("dg_products.id");
$query = $this->db->get();
$result = $query->result();
return $result;
}
Try it like this :
$this->db->select('dg_products.*, AVG(`dg_rating.rating`) As averageRating');
you just have an unneeded quotes in there.

data repeating when two tables are joined in codeigniter

I tried to fetch data using joins and the data is repeating,
The controller code is:
public function searchjobs2()
{
//$id=$_SESSION['id'];
$lan = $_POST["picke"]; //var_dump($id);die();
$value['list']=$this->Free_model->get_jobs($lan);//var_dump($value);die();
$this->load->view('free/header');
$this->load->view('free/searchjobs2',$value);
}
And the model:
public function get_jobs($lan)
{
$this->db->select('*');
$this->db->from("tbl_work_stats");
$this->db->join("tbl_work", "tbl_work.login_id = tbl_work_stats.login_id",'inner');
$this->db->where("language LIKE '%$lan%'");
// $this->db->where('tbl_work_stats.login_id',$id);
$this->db->order_by('insertdate','asc');
$query=$this->db->get()->result_array();//var_dump($query);die();
return $query;
}
I have used
foreach ($list as $row){
...
}
for listing.
Using distinct will remove duplicate fields:
$this->db->distinct();
From what I can see, your query has ambiguity, and an error in the join statement, also your where like is part of the problem, I would recommend trying this even do there are some missing info, find out wich field you need to join from the second table.
public function get_jobs($lan){
$this->db->select("tbl_work_stats.*, tbl_work.fields");
$this->db->from("tbl_work_stats");
$this->db->join("tbl_work", "tbl_work_stats.login_id = tbl_work.login_id","inner");
$this->db->where("tbl_work.language LIKE", "%" . $lan . "%" );
$this->db->order_by("tbl_work_stats.insertdate","asc");
$query=$this->db->get()->result_array();
return $query;}
do you mean to join on login_id?
I am guessing that is the user logging in and it is the same for many entries of tbl_work_stats and tbl_work.
you didn't post your schema, , but login_id doesn't seem like right thing to join on. how about something like tbl_work.id = tbl_work_stats.tbl_work_id or similar?
also CI $db returns self, so you can do:
public function get_jobs(string $lan):array
{
return $this->db->select()
->from('tbl_work_stats')
->join('tbl_work','tbl_work.id = tbl_work_stats.work_id')
->like('language',$lan)
->order_by('insertdate')
->get()
->result_array();
}

Only last row getting displayed in view in Codeigniter

I'm trying to fetch certain values from and then pass it to another model in the same control.
However I'm only able to display the last row in the view.
I have shared my code below and I'm not sure where I'm going wrong.
Controller:
public function test($id){
$mapping_details = $this->queue_model->get_mapping_details($id);
foreach ($mapping_details as $value) {
$data['agent_details'] = array($this->agent_model->get_agent_details($value['user_id']));
}
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Model:
public function get_agent_details($id) {
$query = "select * from user_table where id = ".$id." and company_id = ".$this->session->userdata('user_comp_id');
$res = $this->db->query($query);
return $res->result_array();
}
Welcome to StackOverflow. The problem is the iteration in your controller. You are iterating through the $mapping_details results and per every iteration you are re-assigning the value to $data['agent_details'] , thus losing the last stored information. What you need to do is push to an array, like this:
foreach ($mapping_details as $value) {
$data['agent_details'][] = $this->agent_model->get_agent_details($value['user_id']);
}
However, wouldn't it be best if you created a query that uses JOIN to get the related information from the database? This will be a more efficient way of creating your query, and will stop you from iterating and calling that get_agent_details() over and over again. Think of speed. To do this, you would create a model method that looks something like this (this is just an example):
public function get_mapping_details_with_users($id){
$this->db->select('*');
$this->db->from('mapping_details_table as m');
$this->db->join('user_table as u', 'u.id=m.user_id');
$this->db->where('m.id', $id);
$this->db->where('u.company_id', $this->session->userdata('user_comp_id'));
return $this->db->get()->result();
}
Then your controller will only need to get that model result and send it to the view:
public function test($id){
$data['details_w_users'] = $this->queue_model->get_mapping_details_with_users($id);
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Hope this helps. :)

CodeIgniter COUNT with active record?

I am working in codeigniter.. I want to count the no. of rows having the same order_no.. below is my code.
public function get_my_orders() {
$user_data = $this->session->all_userdata();
$email = $user_data['user_email'];
$this->db->select('*');
$this->db->from('order_details');
$this->db->where('email', $email);
$this->db->group_by('order_no');
$this->db->order_by('order_no', 'DESC');
$query = $this->db->get();
return $query->result();
}
Pls help..
You can use $this->db->count_all_results()
public function get_my_orders() {
$user_data = $this->session->all_userdata();
$email = $user_data['user_email'];
//$this->db->select('*');// no need select as you only want counts
$this->db->from('order_details');
$this->db->where('email', $email);
//$this->db->group_by('order_no');//no need group_by as you only want counts
//$this->db->order_by('order_no', 'DESC');//no need order_by as you only want counts
return $this->db->count_all_results();;
}
Try changing your select line to look like this:
$this->db->select('COUNT(*) as count');
Rather than having all fields accessible like they currently are, you will instead only have access to one variable called count. To keep all variables accessible and add the count in as well, use this instead:
$this->db->select('*, COUNT(*) as count');
Feel free to change the lowercase name for count, I'm just using that as an example.
Check Codeigniter Manual
$query = $this->db->get();
return $query->num_rows(); //Return total no. of rows here
$query->num_rows(); will count the total active record return by your query.

Codeigniter count_all for pagination

I'm trying to create pagination in codeigniter and I have it working, but I have a small issue. It seems to be loading all the entries in my database and not the selected ones I want.
public function original_count() {
$this->db->where('type', 'Original');
return $this->db->count_all("story_tbl");
}
I know that whats happening is that the last line is overrighting my previous statements. I can't seem to find a way around it though. I tried just a staight sql statement and then returning it, but I could not get that to work either.
this was my statement...
SELECT COUNT(*) FROM story_tbl where type = 'Original';
Some help would much appreciated! :)
CI has inbuilt count method
count_all_results()
Permits you to determine the number of rows in a particular Active Record query. Queries will accept Active Record restrictors such as where(), or_where(), like(), or_like(), etc. Example:
https://www.codeigniter.com/userguide2/database/active_record.html
$total_count = $this->db->count_all_results('story_tbl', array('type' =>'Original'));
You could also use the built-in num_rows() function...
$query = $this->db->where('type', 'original')->get('story_tbl');
return $query->num_rows();
First Try this one.
$query = $this->db->where('tbl_field', 'value')
->get('your_table');
return $query->num_rows();
Besides this Codeigniter has it own function like the following.
$this->db->where('tbl_field', 'value')
->get('your_table');
return $this->db->count_all_results();
Or use this.
return $this->db->count_all('your_table');
Where wont work on count_all condition.. you can use below method to find out total number of rows..
public function count_all() {
$this->db->select ( 'COUNT(*) AS `numrows`' );
$this->db->where ( array (
'type' => 'Original'
) );
$query = $this->db->get ( 'story_tbl' );
return $query->row ()->numrows;
}

Categories