Save the total sum in my table (codeigniter) - codeigniter

Newbie at codeigniter here. how can I save my total amount in my table per user? The only thing I did is to sum it and show it on my view. My target is to save the total commission on my "agent_commission" table". I have provided a screenshot of my target for better visualization. Thank you in advance. Any help will be appreciated.
Views:
<?php $formattedNum = number_format($commCurrentBalance, 2);
echo $formattedNum;
?
Controller:
public function commi()
{
$data['activeNav'] = "";
$data['subnav'] = "commissions";
$this->header($data);
$this->nav();
$data['currentPoints']=$this->session->userdata('currentPoints');
$data['result'] = $this->commissions->get1();
$data['commCurrentBalance']=$this->load->commissions->gettotalcommi(); //getting sum of amount
$this->load->view('comm_view', $data);
$this->footer();
}
Model:
function gettotalcommi(){
$reqcommi= $this->session->userdata('uid');
$this->db->select_sum('amount');
$this->db->where('commTo',$reqcommi);
$result = $this->db->get('agent_commission_history')->row();
return $result->amount;
}

I'm not sure if it will work but please try
$db->select_sum('amount');
$db->where('commTo',$param);
$aq = $db->get_compiled_select('agent_commission_history');
$db->set('commCurrentBalance',"($aq)",false);
$db->where('commTo',$param2);
$db->update('agent_commission');
This is the Codeigniter equivalent of the query I posted earlier:
UPDATE agent_commission
SET commCurrentBalance = ( SELECT SUM(amount) FROM agent_commission_history WHERE commTo = ?)
WHERE commTo = ?

public function commi(){
$data['commCurrentBalance']=$this->load->commissions->gettotalcommi(); //getting sum of amount
$dataArray = array(
'commCurrentBalance'=>$data['commCurrentBalance']
);
$this->db->insert('agent_commission',$dataArray);
$this->load->view('comm_view', $data);
$this->footer();
}

Related

Laravel model is updating multiple models instead of single

I am trying to update my model using multiple where conditions.
my code is
public function UpdateEducationData(Request $request)
{
$user = app('user');
// return $request;
$education = eduinfo::where("id", $user->id)->where("exam", $request->type)->first();
// dump sql query for debugging
// $education->rawSql();
// dd($education);
$education->board = $request->board;
// $education->degree = $request->degree;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
// update education based on exam
$education->save();
return redirect()->back()->with("message", "Education Information Updated Successfully");
return "Update Education Data";
}
My code is updating a eduinfo table based on id and exam. But whenever this function is called it updates all eduinfo records related to that user id.
I tried to update eduinfo table single record but multiple records are being update at once. I dumped eduinfo after retriving the model and yes it's retrieving the single model using first() method but still when save() is called it updates all records of that user id in eduinfo.
I think Your conditions to make a unique record are not.
But if you wanna Just run one time! I have an offer to you.
$flag=true;
if($flag){
$user = \Auth::user();
$education = eduinfo::where('id','=', $user->id)->where('exam','=', $request->type)->first();
$education->board = $request->board;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
$education->save();
$flag=false;
}
It's depends on my answer.

How to update a row from a different row data using laravel

By clicking verify button I want the status of payment to change from pending to verified, then the pending amount (in payments table) to sum up with the wallet balance amount in users table and the final balance updated in users table using Laravel. This is my controller. Please help
public function verify_payment($user_id,$payment_data,$id){
$wallet = Mpesa::findOrFail($id);
$wallet->status = 'verified';
if($wallet->save()){
flash(__('Payment has been approved successfully'))->success();
return redirect()->route('all.payments');
}
$top_up = User::findOrFail($user_id);
$top_up->amount = $payment_data['amount'];
$top_up->balance = $top_up->balance + $payment_data['amount'];
$top_up->save();
flash(__('Something went wrong'))->error();
return back();
}
public function verify_payment($user_id,$payment_data,$id){
$wallet = Mpesa::findOrFail($id);
$wallet->status = 'verified';
if($wallet->save()){
flash(__('Payment has been approved successfully'))->success();
}
$top_up = User::findOrFail($user_id);
$top_up->amount = $payment_data['amount'];
$top_up->balance = $top_up->balance + $payment_data['amount'];
$top_up->save();
flash(__('Something went wrong'))->error();
return redirect()->route('all.payments');
}

How to call information from one model to another Codeigniter

I'm stuck on this from a while.Can't figured it out.I reed documantion, tried with several videos and tried like 10 different ways, nothing is working yet.So I have one view/model for one thing, in this example Destination and I have separate files for Offers.The controllers for both are in one file.I want tho the information that is in destination to go to Offers as well.Please help I can't figure out what I'm missing:
So here is the most important parts:
destination_model.php
<?php class Destination_model extends CI_Model
{
public function getDestinationDetails($slug) {
$this->db->select('
id,
title,
information
');
$this->db->where('slug', $slug);
$query = $this->db->get('destinations')->row();
if(count($query) > 0)
{
return $query;
}
else
{
// redirect(base_url());
}
}
public function getOffersByDestination($destination_id)
{
$this->db->select('
o.short_title,
o.price,
o.currency,
o.information,
o.long_title_slug,
oi.image,
c.slug as parent_category
');
$this->db->from('offers o');
$this->db->join('offers_images oi', 'oi.offer_id = o.id', 'left');
$this->db->join('categories c', 'c.id = o.category');
$this->db->group_by('o.id');
$this->db->where('o.destination', $destination_id);
$this->db->where('o.active', '1');
return $this->db->get();
} }
And then in the controller for offers I put this:
$this->load->model('frontend/destination_model');
$this->params['destination'] = $this->destination_model->getOffersByDestination($data->id);
All I need is the title and the information about the destination.
Here is the whole controller for the offers:
$data = $this->slugs_model->getOfferDetails(strtok($this->uri->segment(2), "."));
$this->load->model('frontend/offers_model');
$this->load->model('frontend/destination_model');
$this->params['main'] = 'frontend/pages/offer_details';
$this->params['title'] = $data->long_title;
$this->params['breadcumb'] = $this->slugs_model->getSlugName($this->uri->segment(1));
$this->params['data'] = $data;
$this->params['images'] = $this->slugs_model->getOfferImages($data->id);
$this->params['similar'] = $this->slugs_model->getSimilarOffers($data->category, $data->id);
$this->params['destination'] = $this->destination_model->getOffersByDestination($data->id);
$this->params['offers'] = $this->offers_model->getImportantOffers($data->offers, $data->category, $data->id);
You need to generate query results after you get it from model,
e.g: row_array(), this function returns a single result row.
here's the doc: Generating Query Results
try this:
$this->load->model('frontend/destination_model');
$data['destination'] = $this->destination_model->getOffersByDestination($data->id)->row_array();
$this->load->view('view_name', $data);
And in your view echo $destination['attribut_name'];,
or you can print the array, to see if it's work print_r($destination);

jquery datatable with ajax based pagination

I have javascript function that populates datatable using Ajax. My javascript code looks like :
$('#results').dataTable({
// Ajax load data
"ajax": {
"url": "get_intl_tickets",
"type": "POST",
"data": {
"user_id": 451,
"csrfmiddlewaretoken" : csrftoken,
}
}
})
My server side script in django has a function that loads around 500 data rows. Now the problem is that I don't want to load whole data at a time. Instead I want to have first 10 data rows. Then with pagination, another 10 rows like that.
I read the page server side processing documentation of datatables. I tried with "serverSide": true option as well. I am not understanding server side script. There is given an example of PHP. It seems that they are not using any parameters like draw, recordsFiltered, recordsTotal there. There they have used php SSP class. And it is unknown what does it do. I am trying to implement it in django.
But I am not finding proper good documentation to implement. Any help will be appreciated.
Old question but one I also had a surprisingly difficult time finding an answer to, so in case anyone else ends up here... :P
I found this 2020 article very helpful, specifically part 6 showing the "complete code" that includes getting the correct variables, building the SQL query, and how to build/structure the data object that it responds with:
https://makitweb.com/datatables-ajax-pagination-with-search-and-sort-php/
Their example posted below:
<?php
## Database configuration
include 'config.php';
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($con,$_POST['search']['value']); // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " and (emp_name like '%".$searchValue."%' or
email like '%".$searchValue."%' or
city like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of record with filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
Nice exemple:
https://datatables.net/examples/server_side/defer_loading.html
But you need edit server side.
Response demo
{
draw:2,
recordsFiltered:57,
recordsTotal:57
}

codeigniter pagination total_rows dynamically

here is my code and my problem in comment line.
public function sonuc()
{
$config['total_rows'] = 5 //i want to set here count of result instead of digit. count($data['sonuc']) does not work.. what will i do?
$config['per_page'] = 2;
$data['sonuc'] = $this->emlak_model->arama(
$config['per_page'],
$this->uri->segment(3,0),
$this->input->post('semt'),
);
}
if i do it manually with digit, pagination will work, but i want to get total_row of query automatically, what will i do? thanks.
If you want a fresh count of your field on each page load,you have to count all your fields with a query count:
$total_rows = $this->db->count_all_results('mytable');
check the Codeigniter Doc
so according to your code:
public function sonuc()
{
$config['total_rows'] = $this->db->count_all_results('mytable'); //put your table name here
$config['per_page'] = 2;
$data['sonuc'] = $this->emlak_model->arama(
$config['per_page'],
$this->uri->segment(3,0),
$this->input->post('semt'),
);
}

Resources