I have two database tables, one for allowances and one for deductions. I want to calculate net salaries.
I'm using CodeIgniter. Here's my current code:
function get_allowances($eid)
{
$this->db->from('allowances');
$this->db->where('eid',$eid);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$salary_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('allowances');
foreach ($fields as $field)
{
$salary_obj->$field='';
}
return $salary_obj;
}
}
function get_deductions($eid)
{
$this->db->from('deductions');
$this->db->where('eid',$eid);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$salary_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('deductions');
foreach ($fields as $field)
{
$salary_obj->$field='';
}
return $salary_obj;
}
}
and in controller,
function net_salary($eid)
{
$allownces[] = $this->Salary->get_allowances($eid);
$deductions[] = $this->Salary->get_deductions($eid);
return $net_salary = array_sum($allownces) - array_sum($deductions);
}
My net_salary() function gives me a result of 0. What am I doing wrong, and how can I fix it?
Your models with plural names are only going to return a single object.
so what you are ending up with is...
Array
(
[0] => allowance_object
)
and
Array
(
[0] => deduction_object
)
While we really need the schema of your database try this (and make same edits for deductions)...
function get_allowances($eid)
{
$this->db->from('allowances');
$this->db->where('eid',$eid);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row_array(); //<--- return an Array
}
else
{
// make an array instead of object
$salary_obj = array();
//Get all the fields from items table
$fields = $this->db->list_fields('allowances');
foreach ($fields as $field)
{
$salary_array[$field] = 0; //<---- add array keys and set to integer 0 instead of empty string.
}
return $salary_array;
}
}
then in your net_salary function
function net_salary($eid)
{
$allownce = $this->Salary->get_allowances($eid);
$deduction = $this->Salary->get_deductions($eid);
return array_sum($allownce) - array_sum($deduction);
}
Try something like this:
function get_values($eid, $table_name)
{
$this->db->where('eid',$eid);
$query = $this->db->get($table_name);
$salary_obj = $query->result();
$values = array();
foreach($salary_obj as $row){
$values[] = $row->value_column_name;
}
return $values;
}
where value_column_name is the name of the table column (filedname) where the desired value stands.
call in controller:
function net_salary($eid)
{
$allownces = $this->Salary->get_values($eid, 'allowances');
$deductions = $this->Salary->get_values($eid, 'deductions');
return $net_salary = array_sum($allownces) - array_sum($deductions);
}
Related
This is my addToCart method in which I am adding the courses to user_cart column in users table.
public function addToCart($id){
$course = Course::findOrfail($id);
$user =Auth::user();
$cart_array = array();
$cart = $user->user_cart;
if ($cart == '') {
array_push($cart_array, array('id' => $course->id));
// print_r($cart_array);
} else {
$founder = false;
$cart_array = json_decode($cart, true);
for ($i = 0; $i < count($cart_array); $i++) {
$cart_for_eacch_course = $cart_array[$i];
if ($cart_for_eacch_course['id'] == $course->id) {
$founder = true;
}
}
if (!$founder) {
array_push($cart_array, array('id' => $course->id));
}
}
$data['id'] = json_encode($cart_array);
$update = User::where('id',$user->id)->update(['user_cart'=> $cart_array]);
return redirect()->back();
}
And this is my showcart method in which I am taking the courses from users table user_cart column array.
public function showcart(){
$user = Auth::user();
$array = $user->user_cart;
print_r($array);
return view('frontend.my_cart', compact('academic','nonacademic','instructor','coc','my_cart'));
}
And when I am displaying it I am getting the output as follows:
[{"id":84},{"id":86}]
Now can you tell me that how to loop them so I can get the courses? I tried by using a foreach loop for $array but it shows me the error of invalid argument supplied for foreach()
Looks like you are building the array into a JSON or string field within your database on the User object. The resulting array appears to be stored as a JSON string, so decode and then loop:
$array = json_decode( $user->user_cart, true );
foreach($array as $key => $val){
dump $key;
dump $val;
}
I want to make a query that results like this in codeigniter MODEL:
$caldata = array (
15 => 'yes',
17 => 'no'
);
Is that possible to do?
Take NOTE: The 15,17 and yes,no are in the same database table.
There is no core helper function to achieve what you want in CI. But you can create your own helper function:
function pluck($arr = [], $val = '', $key = '')
{
// val - label for value in array
// key - label for key in array
$result = [];
foreach ($arr as $value) {
if(!empty($key)){
$result[$value[$key]] = $value[$val];
}else{
$result[] = $value[$val];
}
}
return $result;
}
you can use result_array() function so you can have something like:
$query = $this->db->select('id,answer')->from('users')->get();
$result = $query->result_array();
print_r($result);
After that you have your array and you can make the $key => $value relation of the fields
After a long search i found an answer. Sample way to do this:
$query = $this->db->select('start_date, class')->from('event')->like('start_date', "$year-$month", 'after')->get();
$datavariable = $query->result();
$caldata = array();
foreach($datavariable as $row){
$caldata[substr($row->start_date,8,2)] = $row->class;
}
I have a table of item and a table cart. What I'm trying to do is fetch all instances of item and cart then I put them in the loop such that whenever the item's item_id matches the cart's item_id, I'll subtract cart's item_quantity value from item's number_of_units. The result is then used to update item's number_of_items. There's seems to be a problem with my nested foreach loop.
Here's a function in my controller
public function checkout(){
$this->load->model('HomeModel');
$x['item'] = $this->HomeModel->displayAllItems();
$y['cart'] = $this->HomeModel->displayAllCartItems();
foreach($x['item'] as $item){
foreach($y['cart'] as $cart){
if(($item->item_id) == ($cart->item_id)){
$temp1 = $item->number_of_units;
$temp2 = $cart->item_quantity;
$temp = $temp1 - $temp2;
$z = array(
'number_of_units' => $temp,
);
$this->HomeModel->updateItem($z, $item->item_id);
}
}
}
}
Here's some of my model functions:
public function displayAllCartItems()
{
$query = $this->db->select('*')->from('cart')->get();
return $query->result();
}
public function displayAllItems()
{
$query = $this->db->select('*')->from('item')->get();
return $query->result();
}
public function updateItem($data, $id)
{
$this->db->where('item_name', $id);
$query = $this->db->update('item', $data);
}
I want to pass multiple id in where condition how to do it?
A query fetches org_id from database.
now I want to pass that in my where condition, so how to do it?
I tried foreach loop:
Below is my code:
$devices = $this->activation_m->get_activated_devices();
$org_id = array(); // create org_id array
foreach ($devices as $row)
{
$org_id[]= $row['org_id']; // assign ids into array
//$companys =$this->data['devices'] = $this->activation_m->get_company($org_id); // don't call again and again
}
//Now $org_id is array
$companys =$this->data['devices'] = $this->activation_m->get_company($org_id);
echo $this->db->last_query();
Model Code
public function get_activated_devices()
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.site_key = activation.site_key');
$this->db->from('activation');
$query =$this->db->get();
$result = $query->result_array();
return $result;
}
public function get_company($org_id)
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
$this->db->where('company.id IN',(implode(',',$org_id))); // see the change here
$this->db->from('company');
$query =$this->db->get();
$result = $query->result_array();
return $result;
}
now currently my query passes only one org_id , I want to pass all the org_id I get from my first query.
You can use where_in from active-records codeigniter
as
$devices = $this->activation_m->get_activated_devices();
$org_id = array();
foreach ($devices as $row)
{
$org_id[] = $row['org_id'];
}
$companys =$this->data['devices'] = $this->activation_m->get_company($org_id);
if( $companys->num_rows() > 0 )
{
echo "<pre>";
print_r( $companys->result());
echo "</pre>";
}
And for Model
public function get_company($org_ids = array())
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
$this->db->where_in('company.id', $org_ids ); //this is condition
$this->db->from('company');
return $this->db->get();
}
You can use codeigniter's $this->db->or_where() for the purpose. Just traverse the array of organization id's and apply or_where conditions.
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
foreach($org_id as $org)
{ // where $org is the instance of one object of active record
$this->db->or_where('company.id',$org);
}
$this->db->from('company');
$query =$this->db->get();
$result = $query->result_array();
return $result;
Another way to do this is to make a custom query by traversing the array like this and appending where clauses in string.
I am new to Codeigniter and have managed to build an app where I have used 'implode' method to insert multiple files in db table in single column.
I am trying to figure out how to delete a single selected file from this column. I think I should be using something like 'Explode' or I am not sure.
In column files appear as:
image1.jpg,image2.jpg,image3.jpg,image4.jpg,image5.jpg
So far I have controller:
function property_image_delete() {
$id = $this->uri->segment(3);
$image = $this->uri->segment(4);
$data['images_urls'] = $this->my_listings_model->get_property_all_images_url($id);
$this->my_listings_model->delete_selected_property_image($id, $image, $data);
$data['title'] = 'Image Deleted';
$this->load->view('view');
url appear as:
localhost/dashboard/property_image_delete/1/image.jpg
Model:
function delete_selected_property_image($id, $image, $data) {
$this->db->select('property_images', $image);
$this->db->where('property_ref_id', $id);
$this->db->delete('vbc_property_images');
unlink('uploads/property-images/'.$image);
return TRUE;
}
function get_property_all_images_url($id) {
$this->db->select('property_images');
$this->db->from('vbc_property_images');
$this->db->where('property_ref_id', $id);
$query = $this->db->get();
$query_result = $query->result_array();
if (empty($query_result)) {
return FALSE;
}
elseif (count($query_result) > 1) {
return 0;
}
else{
$rowId = explode(',',$query_result[0]['property_images']);
return $rowId;
}
}
After your comments, i am sharing a basic idea for this, you can implement this with your CI Queries.
// a file that you want to delete.
$Delete = "image3.jpg";
// Existing Column Data , that you get from your DATABASE by using SELECT Query
$yourColumnValue = "image1.jpg,image2.jpg,image3.jpg,image4.jpg,image5.jpg";
// explode with , you will get this data in an array
$explodeArr = explode(",", $yourColumnValue);
$updatedColumn = "";
foreach ($explodeArr as $key => $value) {
if($value != $Delete){
$updatedColumn[] = $value; // store data that you dont need to delete
}
}
What is the result of $updatedColumn:
echo "<pre>";
print_r($updatedColumn);
Array
(
[0] => image1.jpg
[1] => image2.jpg
[2] => image4.jpg
[3] => image5.jpg
)
// final updated data with comma seperated.
$newUpdatedData = implode(",", $updatedColumn);
And the result of $newUpdateData should be:
image1.jpg,image2.jpg,image4.jpg,image5.jpg
Now Use CI UPDATE Statement:
$this->db->where('property_ref_id', $id);
$this->db->update(array('vbc_property_images'=>$newUpdatedData));
What should be happened?
After this you don't need to DELETE any record, you can just update the existing record by using UPDATE Statement.
Try this. In the controller:
function property_image_delete($id, $image) {
$this->my_listings_model->delete_selected_property_image($id, $image);
$data['title'] = 'Image Deleted';
$this->load->view('view');
}
Then in your model:
function delete_selected_property_image($id, $image) {
//get the string of images names
$this->db->select('property_images');
$this->db->where('property_ref_id', $id);
$query = $this->db->get('vbc_property_images');
$result = $query->result();
//turn the string into an array with explode
$images_array = explode(',', $result->property_images);
//find and remove the unwanted image name from the array
if(($key = array_search($image, $images_array )) !== false) {
unset($images_array [$key]);
}
//update the database with the imploded new array
$this->db->where('property_ref_id', $id);
$this->db->update(array('vbc_property_images'=>implode(',', $images_array)));
//delete the file
unlink("uploads/property-images/{$id}/{$image}");
return TRUE;
}
Controller
function property_image_delete() {
$id = $this->uri->segment(3);
$image = $this->uri->segment(4);
$data['images_urls'] = $this->my_listings_model->get_property_all_images_url($id);
// $data['images_urls'] // <-- !!! is an array?
$this->my_listings_model->delete_selected_property_image($id, $image, $data['images_urls']);
$data['title'] = 'Image Deleted';
$this->load->view('view');
}
Update your model function!
function delete_selected_property_image($id, $image,$urls) {
$this->db->select('property_images', $image);
$this->db->where('property_ref_id', $id);
$query = $this->db->get('vbc_property_images');
if ($query && $query->num_rows() > 0){
$row = $quer->row();
$images = explode(',',$row->property_images);
if(($key = array_search($image, $images)) !== false) {
unset($images[$key]);
unlink($urls[$image]); // <--- **EDITED**
}
else
return false;
$images = implode(',',images);
$data = array(
'property_images' => $images
);
$this->db->where('property_ref_id', $id);
$this->db->update('vbc_property_images',$data);
return true;
}
return false;
}