Get the total/sum of commission per user and display it - codeigniter

My target is to display the total commission per user. I tried it already but the only thing I'm getting is commission of myself which is 503,582.26. I want to display the commission dynamically. For example: ID 1 = 500, ID 2 = 300, ID = 600. I have provided screenshot below for more explanation. Any help will be appreciated. Thank you
Views:
<?php
foreach($result as $rows) { $uuid = $rows->uuid;
$userID = $rows->userID; ?>
<?php if($rows->uuid===$_SESSION['uid']): ?>
<tr>
<td><?php echo $rows->firstname; ?></td>
<td><?php echo $rows->mobile; ?></td>
<td><?php echo $rows->account_type; ?></td>
<td><?php echo $rows->currentPoints; ?></td>
<td> <?php $sum = number_format($commBalance -$commWithdrawn,2); echo ($sum);?></td>
<td>
Controller:
public function agents()
{
$data['activeNav'] = "";
$data['subnav'] = "networks";
$this->header($data);
$this->nav();
$data['result'] = $this->networks->getAllData();
$data['commBalance']=$this->load->networks->gettotalcommi();
$data['commWithdrawn']=$this->load->networks->gettotalWithdrawn();
$data['meronResult'] = $this->networks->meronBets();
$data['walaResult'] = $this->networks->walaBets();
$data['tagent']=$this->load->networks->gettotalagent();
$this->load->view('agents', $data);
$this->footer();
}
Model:
function gettotalcommi(){
$reqcommi= $this->session->userdata('uid');
$a = $this->input->post('userID');
$this->db->select_sum('amount');
$this->db->where('commTo',$reqcommi);
$bind = array('commType', 'in');
$this->db->where_in('commType', $bind);
$result = $this->db->get('agent_commission_history')->row();
return $result->amount;
}
function gettotalWithdrawn(){
$a = $this->input->post('userID');
$reqcommi= $this->session->userdata('uid');
$this->db->select_sum('amount');
$this->db->where('commTo',$reqcommi);
$bind = array('commType', 'out');
$this->db->where_in('commType', $bind);
$result = $this->db->get('agent_commission_history')->row();
return $result->amount;
}

If I understand correctly, you want retrieve data by post value USERID. And also show the individual 'contributions'.
What i'm seeing in your implementation, is that your summing all contributions by USERID 1 for example, but not grouping the values by individual contributors or retrieving the individual contributor values.
Group by agent example:
function gettotalcommi(){
return $this->db->select_sum('amount')
->from('agent_commission_history')
->where('commTo', $this->session->userdata('uid'))
->where_in('commType', ['commType', 'in'])
->group_by('commFrom')
->get()->row()->amount;
}
Individual get:
function gettotalcommi(){
return $this->db->select_sum('amount')
->from('agent_commission_history')
->where('commTo', $this->session->userdata('uid'))
// individual
->where('commFrom', $this->input->post('userID'))
->where_in('commType', ['commType', 'in'])
->get()->row()->amount;
}
I hope this helps. If i'm misinterpreting your question, lemme know.

Related

Codeigniter framework: How do we trace where the variables in a given 'view' php code snippet are coming from?

I am in a codeigniter project, examining a file in the views folder. The php is as follows:
As a complete beginner, trying to make sense of this, I am trying to change the value of 'username' below to the 'firstname' that is a different field in the database. Changing the field below, from username, to firstname, causes an error.
I notice there is a loop using the variable: $results as $result)
What I want to know -as a lay person - is how to trace back where these variables are being 'called'from and which files to look into in order to find out how to use the required field, in this case, firstname, which is also from the database.
I have looked into the controllers, but can find nothing resembling this and don't know where to start, as the developer hasn't necessarily labelled everything logically.
My question is: As someone coming into a codebase that they don't know, how do you go about tracing back the logic to find out where you need to look to change a variable and make a change.
Any help on this matter would be greatly appreciated.
<?php
$rank = 0;
foreach($results as $result){$rank++;
?>
<tr style="border: 1px solid #ebebeb;padding-bottom: 0px;background-color: #fff;">
<td ><?php echo $rank; ?></td>
<td ><?php echo $result->username; ?></td>
<td ><?php echo $result->marks; ?></td>
<td ><?php echo $result->percentage; ?></td>
<td ><?php echo $result->duration; ?></td>
<td ><?php echo $result->date_time; ?></td>
<td>
<?php /*<i class="glyph-icon tooltip-button demo-icon icon-edit" title="Edit" style="color:blue;" data-original-title=".icon-edit"></i>
*/?>
<a onclick="return confirm('Are you Sure to Delete this Result???');" href="<?php echo site_url('result/delete/'.$result->id); ?>"><i class="glyph-icon tooltip-button demo-icon icon-close" title="Delete" data-original-title=".icon-close" style="color:red;"></i></a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
<?php } ?>
The starting code on the page I mention is below: Again, notice $results. What is it? Where do I identify its origin and seek to find the fields that populate it?
<?php if(empty($results)) {?>
<div id="page-title">
<h2>No Results Found.</h2>
</br>
</div>
<?php } else { ?>
<div id="page-title">
<h2>All Results</h2>
<h3>Quiz : <?php echo $results[0]->quiz_name; ?></h3>
Delete All
</br>
</div>
What I have done so far:
I have found the controller that seems to be relating to it - pasted below:
load->model('results');
if(!$this->session->userdata('ID'))
{
$this->session->set_flashdata('noAccess', 'Sorry');
redirect(site_url());
}
}
public function index($id='')
{
$data['results'] = $this->results->get_resultByQuiz(-1);
$this->load->view('template/header.php');
$this->load->view('result/index.php',$data);
$this->load->view('template/footer.php');
}
public function view($id='')
{
$data['results'] = $this->results->get_resultByQuiz($id);
$this->load->view('template/header.php');
$this->load->view('result/index.php',$data);
$this->load->view('template/footer.php');
}
public function delAll($id = '')
{
$updated = $this->results->delAll($id);
if($updated)
{
$this->session->set_flashdata('resultDeleteSuccess','result');
}
else
{
$this->session->set_flashdata('resultDeleteFail','result');
}
redirect('quiz');
}
public function delete($id = '')
{
$updated = $this->results->delete_results($id);
if($updated)
{
$this->session->set_flashdata('deleteSuccess','result');
}
else
{
$this->session->set_flashdata('deleteSuccess','result');
}
redirect('result');
}
}
I have also found this related model.
<?php if(!defined('BASEPATH')) exit ("No direct script access allowed");
class Results extends CI_Model {
public function get_all_results()
{
$query = $this->db->get('quiz_takers');
return $query->result();
}
public function get_resultByQuiz($ID)
{
$query = $this->db->query("select (select quiz_name from quizes where id = qt.quiz_id) as quiz_name, qt.* from quiz_takers qt where qt.quiz_id = '$ID' order by qt.percentage desc ");
return $query->result();
$this->db->where('quiz_id',$ID);
$query = $this->db->get('quiz_takers');
return $query->result();
}
public function delAll($ID = '')
{
$this->db->where('quiz_id',$ID);
return $this->db->delete('quiz_takers',$data);
}
public function delete_results($ID = '')
{
$this->db->where('id',$ID);
return $this->db->delete('quiz_takers',$data);
}
}
I am still none the wiser in determining where to alter what is held in that $results variable, so that I can change the field from username to firstname.
I suspect it may have something to do with this:
return $query->result();
but where do I search for queries? In models/controllers - or somewhere else?
In codeigniter,
view is where you write the code to be seen on front-end.
model is where you write your DB queries.
controller is where you connect your view and model(front-end
with DB) ie it works as an intermediate. Also, the routes are
generated as your controller-name and then your function-name plus any additional parameter you provided to that function.
So, if your route(URL) is
your-website/controller_name/function_name/additional-parameter
you need to look at the function {function_name} in your controller {Controller_name}.
Sometimes you might see that the controller or the function is not present in the location as it should(from the URL) then you need to check if any route is provided for that particular URL which will be available at application->config->routes.php
Say if your URL is
www.site/xyz
$route['xyz'] = 'controller_name/function_name'; // route set in routes.php
You need to look for function {function_name} in your controller {Controller_name}.
You need not worry about the model or view as they're called and loaded in the controller itself.
Now, about $results,
it is the key provided to the array variable in the controller which acts as variable in the view. See example -
Controller
$data['xyz'] = 'some-value'; // or $whatever['xyz'];
$data['abc'] = 'any-value'; // ...
$this->load->view('some_folder/some_view', $data); // pass $data array or $whatever
View (located at view->some_folder->some_view.php)
echo $xyz; // output: some-value -- key {xyz} of $data becomes a variable
echo $abc; // output: any-value -- key {abc} of $data becomes a variable
For more details, you might wanna look here, here and here.
See if it helps you.

Want to display db value in my page. The Add and view should in one page

public function unit_list()
{
//Redirect in case of session out
if (!$this->session->userdata ( 'user_id' )) {
redirect ( $this->config->base_url (), 'refresh' );
return false;
}
$this->load->model('Unit_model');
$arrWhere = array("vchr_unit_status"=>"A");
$data ["unit"]=$this->Unit_model->get_all($arrWhere);
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('unit/manage',$data);
$this->load->view('includes/footer');
}
This is my controller . The unit_list is the function i wrote to get all data from db and view that in my view page
class Unit_model extends CI_Model{
protected $strTableName = 'suc_unit';
function __construct(){
parent::__construct ();
$CI = &get_instance();
$this->db->from($this->strTableName);
}
/**
*
*/
function get_all($arrWhere)
{
$this->db->where($arrWhere);
$q1 = $this->db->get();
$result = $q1->result_array();
return $result;
}
This is my model
<table id="tblListOfUnits" class="table table-bordered table-striped">
<tr>
<th style="width: 10px">Sl No</th>
<th>Unit Name</th>
<th>Unit Symbol</th>
</tr>
<?php
if(!isset($unit)){
$count = 1;
foreach ($unit as $key => $units) {
?>
<tr id="tr_<?php echo $units->pk_int_unit_id; ?>">
<td id="tdUntSlNo_<?php echo isset($units) ? $units['int_no_decimal']: ' '; ?>><a href="javascript:unitEdit(<?php echo $unit->pk_int_unit_id; ?>)" ><?php echo $count; ?>.</a></td>
<td id="tdUntNme_<?php echo $units->pk_int_unit_id; ?>"><a href="javascript:unitEdit(<?php echo $unit->pk_int_unit_id; ?>)" ><?php echo $unit->vchr_unit_name; ?></a></td>
<td id="tdUntSymbl_<?php echo $units->pk_int_unit_id; ?>"><a href="javascript:unitEdit(<?php echo $unit->pk_int_unit_id; ?>)" ><?php echo $unit->vchr_unit_symbol; ?></a></td>
</tr>
<?php
$count ++;
}
}?>
</table>
This is my view page. please help me to view all the data in my view page. Im new to codeigniter so i dont know how to use get_all function to view the data in my page.
CodeIgniter allows you to pass the data to the view in a couple of ways. First, if you would simply use the second parameter of the view method, then your data would be available as $unit in the view.
In your code, it seems that you are doing that. That means that in your unit/manage.php view, the result of your query should be available as $unit.
A couple of things though. When you load a model, calls to that model are lowercased.
$this->unit_model->get_all( $arrWhere );
It may not matter, but that line should be:
$data["unit"] = $this->unit_model->get_all( $arrWhere );
I want to point out that in your model's method, you are assuming that you will always have a result, and that's not OK. You need to make sure there's a result before trying to return it. Also, you need to provide a table name to get():
function get_all( $arrWhere )
{
// Make sure $arrWhere is an array
if( ! is_array( $arrWhere ) )
return FALSE;
$this->db->where( $arrWhere );
// Make sure you set the table name!
$q1 = $this->db->get( $this->strTableName );
// Make sure there is a result set!
if( $q1->num_rows() > 0 )
return $q1->result_array();
return FALSE; // or NULL, or array(), or whatever you want.
}
Sure, you are trying to set the table in the constructor of the model, but that would only work for the first query to the database. That's not right, and you should avoid that because typically you don't create a model just for a single query.
function __construct()
{
parent::__construct();
// If you are in a CodeIgniter model, you don't need this line
// $CI = &get_instance();
// This is bad. Don't do this ever.
// $this->db->from($this->strTableName);
}
Now in your view you have a problem. $unit will ALWAYS be set, so when you do this:
if( ! isset( $unit ) ) ...
You will never enter that block of code. What you should be doing there is:
if( ! empty( $unit ) ) ...
In your foreach loop, this code will throw an error:
$units->pk_int_unit_id
It's because you are returning an array of arrays from your db call, so it should be:
$units['pk_int_unit_id']
You've got other instances where you're trying to use an object that is actually an array. Basically anywhere that you have $units-> it should be $units['...'].
If you wany to use an object instead of an array, then inside get_all() you should use:
return $q1->result();
Because result_array() is an array of arrays, but result() is an array of objects.
Anyways, hope this helps.

codeigniter grabbing array from database

I'm new to codeigniter and followed the guides but seem to be missing something. I have a simple database with customer records in it. My first goal in codeigniter is to simple list all my customers.
here is my controller:
public function index()
{
$this->load->model('HomeModel'); //loads the HomeModel model
$data = $this->HomeModel->function1(); //loads the function (function1) from the model
$this->load->view('index', $data);
}
Here is my model:
public function function1()
{
$query = $this->db->get('work_orders');
return $query->result();
}
here is my view:
<table class="table table-bordered table-striped table-highlight" id="invoice-details">
<thead>
<tr>
<th>Work Order ID</th>
<th>Status</th>
<th>Description</th>
</tr>
</thead>
<?php
foreach ($data->result() as $row);?>
<tr class="even gradeC">
<td><a href="/WorkOrders/viewWo/<?php echo $row['id']; ?>">
<?php echo $row['id']; ?></a></td>
<td><?php echo $row['status']; ?></td>
<td><?php echo Logic\System\Lib\Helper::trunc(htmlentities($row['description']), 8); ?></td>
</tr>
<?php endforeach; ?>
</table>
Change on model :
public function function1()
{
$query = $this->db->get('work_orders');
//return $query->result();
return $query->result_array();
}
Change on controller :
public function index()
{
$this->load->model('HomeModel');
//$data = $this->HomeModel->function1();
$data['result'] = $this->HomeModel->function1();
$this->load->view('index', $data);
}
Change on view :
//foreach ($data->result() as $row);
if(is_array($result)&&!empty($result))
foreach ($result as $row);
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function. Here is an example using an array:
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('blogview', $data);
Views : Codeigniter User Guide
And Since you are using array on your view like $row['id'], you got to use result_array on model to return result set array:
This function returns the query result as a pure array, or an empty array when no result is produced. Typically you'll use this in a foreach loop, like this:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
Generating Query Results : Codeigniter
You can use $this->db->join();
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
Produces:
SELECT * FROM blogs
JOIN comments ON comments.id = blogs.id
Go through active record class guide .
Active Record Class
In ur controller,u must pass the values as subarray of data array$data['result'].After which u can simply call it in view as $result .
Controller
$data['result'] = $this->HomeModel->function1();
And In view,
foreach ($result as $row){
<?php echo $row->id; ?>
..
}

Codeigniter search with pagination error

Hello I have a problem with my search in CI. In the first page the results are displayed ok, but on second page it shows a 1064 SQL error.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND cpt_echip.cpt_echip_nr_inventar LIKE '%%' LIMIT 10 , 10' at line 1
Here is the code (functions that are used):
MODEL:
function search($start, $limit){
$match = $this->input->post('search');
$tip_echip = $this->input->post('cpt_tip_echip_nume');
$q = $this->db->query("SELECT * FROM (cpt_echip)LEFT OUTER JOIN cpt_utl ON cpt_utl.cpt_utl_marca = cpt_echip.cpt_utl_marca WHERE cpt_echip.cpt_tip_echip_id = $tip_echip AND cpt_echip.cpt_echip_nr_inventar LIKE '%$match%' LIMIT $start , $limit");
$rezultat = $q->result();
return $rezultat;
}
function num_filter(){
$tip_echip = $this->input->post('cpt_tip_echip_nume');
$this->db->where('cpt_tip_echip_id', $tip_echip);
$q = $this->db->get('cpt_echip');
$number = $q->num_rows();
return $number;
}
CONTROLLER:
function search(){
$data = $this->helpdesk_model->general();
$start_row = $this->uri->segment(3);
$per_page = 10;
if(trim($start_row) == ""){
$start_row = 0;
}
$config['base_url'] = base_url() . '/index.php/helpdesk/search/';
$config['total_rows'] = $this->helpdesk_model->num_filter();
$config['per_page'] = $per_page;
$config['num_links'] = 10;
$config['first_link'] = 'Prima pagina';
$config['last_link'] = 'Ultima pagina';
$this->pagination->initialize($config);
$data['pagini'] = $this->pagination->create_links();
$data['query'] = $this->helpdesk_model->search($start_row, $per_page);
$this->load->view('rezultat', $data);
}
VIEW:
<table border="1">
<tr>
<th>Nr. Inventar</th>
<th>Nume</th>
<th>Utilizator</th>
</tr>
<?php foreach($query as $row): ?>
<tr>
<td><?php echo anchor('helpdesk/detalii_echipament/'.$row->cpt_echip_nr_inventar, $row->cpt_echip_nr_inventar, array('data-fancybox-type'=>'iframe', 'class'=>'fancybox')); ?></td>
<td><?php echo $row->cpt_echip_nume; ?></td>
<td><?php echo $row->cpt_utl_nume; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php echo $pagini; ?>
Without the search and filter, the pagination works fine.
It means the $_POST array is empty. There will not be anything posted when you navigate using links to the second page. You can pass the search data by url or store in session at first submission and use it.
Just check using print_r($_POST) to see what is there $_POST array.

execute sql query in joomla

Hi everyone I did a component for back-end in joomla 2.5, but I have problem to execute the sql query, my variable is empty so it donĀ“t show me nothing.
I have other file and documents, but here the important for my question.
first in my controller.php I have this inside admin file
class BusquedaController extends JController
{
protected $default_view= 'restaurantes';
public function display(){
parent::display();
}
}
in my Model file I have restaurante.php
class BusquedaModelRestaurante extends JModelList{
function getListaRestaurantes(){
$db= JFactory::getDBO();
$sql= "SELECT * FROM #__restaurantes";
$db->setQuery($sql);
return $db->loadObjectList();
}
}
in my controller File I have this
class BusquedaControllerRestaurantes extends JControllerAdmin
{
public function getModel($name = 'Restaurante', $prefix = 'BusquedaModel', $config = array('ignore_request' => true))
{
$model = parent::getModel($name, $prefix, $config);
return $model;
}
function listado(){
$firephp->log('hola');
$view=& $this->getView('restaurantes', 'html');
$model= $this->getModel("restaurante");
$listaMensajes= $model->getListaRestaurantes();
$view->assignRef('resList', $listaMensajes);
$view->display();
}
}
finally in my View File I have a tmpl file with my default.php that show a table
foreach ($this->resList as $item):
$checked=JHTML::_('grid.id', $n, $item->id); ?>
<tr>
<td><?php echo $checked; ?></td>
<td><?php echo $item->id; ?></td>
<td><?php echo $item->nombre; ?></td>
<td><?php echo $item->direccion; ?></td>
<td><?php echo $item->telefono; ?></td>
<td><?php echo $item->web; ?></td>
<td><?php echo $item->tipo; ?></td>
<td><?php echo $item->zona; ?></td>
<td><?php echo $item->metro; ?></td>
</tr>
<?php
but the element reslist is empty, I don't know if I do my component well!!, someone know a tutorial or something to do a component in joomla 2.5
thanks!
Try adding error_reporting(E_ALL) at the beginning of your component, it will hopefully show you what're you doing wrong.
If that doesn't help see what the query returns in getListaRestaurantes() method by simplle
print_r($db->loadObjectList());
jexit();
P.S. In JModels you can use $this->_db to get reference to JDatabase object (instead of JFactory::getDBO())
try this, change $listaMensajes to $this->resList in controller
$this->resList= $model->getListaRestaurantes();
throw a run time exception
try
{
$db->setQuery($query);
$result = $db->loadResult(); // If it fails, it will throw a RuntimeException
}
catch (RuntimeException $e)
{
throw new Exception($e->getMessage());
}
also in controller declare a variable as protected
protected $resList;
assign the values to variable like
$this->resList = $model->getListaRestaurantes();
Take a look at our Joomla Component Creator. I think you will find it useful.
I would recommend sticking to the MVC framework as much as possible and use getItems() etc. Just copy what com_weblinks is doing. Or better yet - let the component creator do it all for you.

Resources