What is the best practice of SUM column values using codeigniter - php

I am currently using below code to sum up numbers of quantity based on a ID
targeting mysql quantity column, just wondering if this is the best practice using codeigniter? or is there a shorter way to execute this.
My Model.php
public function sum_quantity_of_stacks($id){
$query = $this->db->query("SELECT *, SUM(qty) as total FROM stocks WHERE drug_id = '$id'");
return $query->row_array();
}
public function sum_quantity_of_request($id){
$query = $this->db->query("SELECT *,SUM(quantity) as total_request FROM med_request WHERE med_given = '$id' AND status = 'Approved'");
return $query->row_array();
}
Then my view.php
$id = $medicine['ID'];
$data['get_count'] = $this->Medicine_model->sum_quantity_of_stacks($id);
$data['get_request'] = $this->Medicine_model->sum_quantity_of_request($id);
$total_available = $data['get_count']['total'];
$total_given = $data['get_request']['total_request'];
echo $total_available - $total_given;
Above code gives me the current available stocks of my medicine inventory.

No, there are no such way to do that, similar to what are you are doing now.
SELECT other column with SUM feature not possible
But there are a method name select_sum() available in query builder by which you may get SUM only like
public function sum_quantity_of_stacks($id){
$this->db->select_sum('qty','total');
$this->db->where('drug_id',$id);
$query = $this->db->get('stocks');
$res = $query->row_array();
//now SUM is available in $res['total']
return $res['total'];
// or return $query->row_array();
}

Related

When i use if else condition in query based on condition, how can i get that value on view in PHP CODEIGNITER

I am confuse with this problem in mysql, I have two table, "A" and "B"
TableA:
S.No contact1 contact2 status
1 Blbh eeee 1
TAbleB:
S.No Phone1 phone2
1 ddd ssss
From this table i am going to get value, from TableA ia m going to check
if (status == 1)
{
run tableA;
}
else
{
run table b;
}
I am gone a return result of this query. In view, how to get value with respected column name. I have no idea of this, help me to get value in view.
public function contDetails($id){
$check = $this->db->query("SELECT contact_status FROM account WHERE id = '$id' ");
$str = $check->row();
$chk = $str->contact_status;
if($chk == 1){
$query = $this->db->query("SELECT * FROM account WHERE id = '$id'");
}else{
$query = $this->db->query("SELECT * FROM contact_details WHERE user_id = '$id'");
}
$run = $query->num_rows();
print_r($run);
}
You can use in your model
$query = $this->db->get(); //--- run the query ---//
return $query->result() //--- to get result in array of object ---//
and then in your view use foreach loop
foreach($results as $result){
echo $result->columnName;
}
have you already written the query in mysql? If yes and if you are concerned about whether the column name to use exist or not you can use isset...
in your view you can use like the following:
<?php
foreach($results as $result)
{
echo (isset($result['col1']))?$result['col1']:$result['col1_2'];
}
?>
And don't forget to use result_array() instsead of result in the controller

CodeIgniter Active Record - Get number of returned rows and get the sum

I'm new to CodeIgniter and Active Record in particular
How can I Get number of returned rows and get the SUM of two returned tables row counts.
I already have function to get row count like this
controller
function newsletter (){
$data = array();
$data['subscriber_count'] =$this->mod_contactus->count_subscriber();
$data['user_count'] =$this->mod_contactus->count_reg_users();
$this->load->view('admin/admin_newsletter',$data);
}
model
public function count_subscriber() {
return $this->db->get("tbl_subscribers")->num_rows();
}
public function count_reg_users() {
return $this->db->get("tbl_customer_registration")->num_rows();
}
It is not a big deal. You can do something like this. Assist PHP array_sum .This is php manual to array sum You already have the row counts
in your controller
function newsletter (){
$data = array();
$data['subscriber_count'] =$this->mod_contactus->count_subscriber();
$data['user_count'] =$this->mod_contactus->count_reg_users();
$data['count_both'] = array_sum($data);
$this->load->view('admin/admin_newsletter',$data);
}
in your view echo $count_both ;
If that's really your only goal, just execute one query:
$query = $this->db->query("
select
( select count(*) from table_1 ) +
( select count(*) from table_2 )
as total_num_row
from table_1
");
# $query->num_rows()

fetchOne in CodeIgniter

In Zend, I usually use fetchOne to recept my result when I have only one result (string or int) from my query.
For example :
My model (Zend) :
$query = "
SELECT COUNT(*)
FROM user
";
return $this->getAdapter()->fetchOne($query, null, Zend_Db::FETCH_OBJ);
and in my controler (Zend) :
$table = new Application_Model_TUser;
$number = $table->nUser();
echo $number; // return 5
I would like to do the same thing into CodeIgniter... It's possible ? or am i forced to do :
return $this->db->query("SELECT COUNT(*) AS Nb FROM user")->row()->Nb;
You could do:
return $this->db->count_all('user'); // returns int
Or if you want to add conditions use:
$this->db->from('user');
$this->db->where($conditions);
return $this->db->count_all_results(); // returns int
Update: Based on your comment, it would be best to get it like your have written in your question:
return $this->db->query("SELECT COUNT(*) AS Nb FROM user")->row()->Nb;
Or without using query(), in more of an "active record" fashion:
$where = array('userID'=>'1');
$query = $this->db->get_where('user', $where);
$row = $query->row();
return $row->name;

How to pull ALL from database and limit as opposed to specific id?

I know this is simple php,however I am having great trouble getting my logic written out with codeigniter.
I am trying to pull the 12 most recent users and display their info in a view. I have made a 'created_on' field in my database table to track activity of signing up.
When I specify an id in my controller I am able to pull results that I'm passing from my model to my controller and then my view, however it's only pulling one user like so.
MODEL:
public function newest_members()
{
$session = $this->session->userdata('is_logged_in');
$user_id = $this->session->userdata('id');
$query = $this->db->query("SELECT * FROM users WHERE status = 'active' && id = $user_id ORDER BY created_on DESC LIMIT 12");
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data;
}else{
return array();
}
}
CONTROLLER:
public function dashboard()
{
$this->load->library('session');
$this->load->helper('date');
$session_id = $this->session->userdata('id');
$this->load->model('account_model');
$this->load->model('community_model');
$user = $this->account_model->user();
$data['user'] = $user;
$newest_members = $this->community_model->newest_members();
$data['newest_members'] = $newest_members;
$data['main_content'] = 'account/dashboard';
$this->load->view('includes/templates/main_page_template', $data);
}
VIEW:
<?php
foreach($newest_members as $nm)
{
echo $nm['first_name']; echo "<br />"; echo $nm['last_name'];
}
?>
That is pulling the result of the NEWEST member and the one that is signed in. However I want to pull ALL signed in or not so I was trying something like this with my model:
public function newest_members()
{
$query = $this->db->query("SELECT * FROM users WHERE status = 'active' ORDER BY created_on DESC LIMIT 12");
// OR YOU CAN USE THE BELOW
// $query = $this->db->query("SELECT * FROM users ORDER BY `created_on` DESC LIMIT 12");
// YOU ALSO MIGHT WHAT TO ADD WHERE `status` = 'active' (or whatever applies for your db table)
// EITHER SPIT OUT RESULTS OR EMPTY ARRAY
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data;
}else{
return array();
}
thanks in advance.
SELECT TOP 12 FROM users WHERE status = 'active' ORDER BY created_on DESC
I'M using mssql for this,, try it if it help
The codeigniter num_rows() function does not return a boolean value but rather the number of results fetched from the database. There fore your model should insead have :
if($query->num_rows() > 0)
{
...
}
see here for more information
You want to pull the 12 newest active members? You had it right.
SELECT * FROM users WHERE status = 'active' ORDER BY created_on DESC LIMIT 12
Also, you don't want to check if just one row is returning. You want to check if more than zero rows are returning. You need to do this instead:
if($query->num_rows() > 0)
{
$data = $query->result_array();
return $data;
}
Since your using codeigniter it has a wonderful feature called active record that makes working with a database much easier and more secure then writing raw queries as strings which could result in SQL injection. Here is your function below both utilizing active record and returning the results your expecting.
public function newest_members()
{
//Select the 12 newest users
$result = $this->db->where('status', 'active')->order_by('created_on', 'desc')->limit(12)->get('users');
//If results are found return an array otherwise return an empty array
return ($result->num_rows() > 0) ? $result->result_array() : array();
}

Total amount is ok when i enter one record in both tables if i insert 2nd record in 2nd talble than total amount will double

Dear all friends i am new in Codeigniter framework i want total amount by selecting two table data, the problem is that when i enter data in 2nd table than total will double.
function total_amount($booking_no = NULL)
{
$data = array('forwarding_cargo_booking_details.*',
'other_charges.client_amount');
$this->db->select($data);
$this->db->where('forwarding_cargo_booking_details.booking_no',$booking_no);
$this->db->join('other_charges','forwarding_cargo_booking_details.booking_no = other_charges.booking_no','left');
$this->db->select('sum((`bk_m3`*`o_freight_client`)*(`selling_rate`)+`pod_client`+`thc_client`+`caf_client`+`baf_client`+`haulage_client`+`war_risk_client`+`warehouse_client`+`thc_dest_client`+`pp_surcharge_client`+`doc_charges_client`+`client_amount`) as salam', FAlSE);
$query = $this->db->get('forwarding_cargo_booking_details');
if($query->num_rows() > 0)
{
return $query->row();
}
}
Change it to this. Here use derieved query and test if it works ok
function total_amount($booking_no = NULL)
{
$sql_query = "SELECT
forwarding_cargo_booking_details.*,
other_charges.client_amount,
sum((`bk_m3`*`o_freight_client`)*(`selling_rate`)+`pod_client`+`thc_client`+`caf_client`+`baf_client`+`haulage_client`+`war_risk_client`+`warehouse_client`+`thc_dest_client`+`pp_surcharge_client`+`doc_charges_client`+`client_amount`) as amount
FROM forwarding_cargo_booking_details
LEFT JOIN (SELECT booking_no , sum(client_amount) FROM other_charges group by booking_no) as other_charges ON forwarding_cargo_booking_details.booking_no = other_charges.booking_no
";
$query = $this->db->query();
if($query->num_rows() > 0)
{
return $query->row();
}
}
use this code to print the query, and check the query.
$this->db->last_query();
i think you forget to use "Group By" in your query

Categories