execute sql query in joomla - 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.

Related

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

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.

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.

Codeigniter: View foreach call Controller

Error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: calificacione
Message: Invalid argument supplied for foreach()
what is wrong?
In Controller the variable is created: $data['calificacione']
And in the view is called on foreach
My View:
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>Calificacione</th>
</tr>
</thead>
<tbody>
<?php
foreach ($calificacione as $key => $value) {
echo "<pre>";print_r($value);echo "</pre>";
}
?>
<tr>
<td><?php ?></td>
</tr>
<?php } ?>
</tbody>
</table>
My Controller
class Provedore extends CI_Controller{
function __construct()
{
parent::__construct();
$this->load->model(['Provedore_model','Provedor_calificacione_model','Provedor_calificacione_model','Personas_contato_model','Direcione_model']);
}
/*
* Listing of all provedores
*/
function index()
{
$data['provedores'] = $this->Provedore_model->get_all_provedores();
$data['calificacione'] = $this->Provedor_calificacione_model->get_all_provedor_calificaciones();
$data['_view'] = 'provedore/index';
$this->load->fullView('layouts/main',$data);
}
Please check below mentioned possibilities.
Are you getting data from model or any error.
var_dump($data['calificacione']);
die;
$data['_view'] = 'provedore/index';
$this->load->fullView('layouts/main',$data);
Please share your output so we can help you.
in your model Provedore_model get_all_provedores may has some arguments like
function get_all_provedores ($argument)
{
// your database query
}
and you did'nt fulfilling that argument
//try this
function index()
{
$provedores = $this->Provedore_model->get_all_provedores();
$data['provedores'] = $provedores;
$calificacione = $this->Provedor_calificacione_model->get_all_provedor_calificaciones();
$data['calificacione'] = $calificacione;
$this->load->view('layouts/main',$data)
$this->load->view('provedore/index',$data)
}

Insert Grocery Crud into another crud in codeigniter

i want to insert grocery crud in to another crud table.can i do it? i have tried it but it shows two error called
"Undefined property: Boq_doc_controller::$project_list_model" and
"Fatal error: Call to a member function show_boq_id() on null in
C:\xampp\htdocs\rcj-constructions\back-end\application\controllers\boq_doc_controller.php on line 42".
simply there is top level crud and there is a view boq button instead of edit or delete button.once click the view boq button it should go to the grocery crud.i will add my code. any one can plz help me.
thank you.
my top level crud model
class Project_list_model extends CI_Model {
public function get_all_project(){
$this->db->select("project.project_name, project.id, client.firstname, client.lastname,staff.firstname, staff.lastname, project.location,project.category, project.start_date, project.end_date");
$this->db->from('project');
$this->db->join('client', 'project.client_id = client.client_id');
$this->db->join('staff', 'staff.id = project.staff_id');
$query = $this->db->get();
return $query->result();
}
}
my top level crud controller
public function index()
{
$data['project_list'] = $this->project_list_model->get_all_project();
$this->load->view('project_list_view', $data);
}
my top level crud view
<?php foreach ($project_list as $project){ ?>
<tr>
<td><?php echo $project->project_name; ?></td>
<td><?php echo $project->location; ?></td>
<td width="40" align="left" ><a href="<?php echo base_url();?>index.php/project_list/index" >view BOQ</a></td>
</tr>
<?php }?>
my grocery crud controller
function __construct()
{
parent::__construct();
//load the Grocery_CRUD library
$this->load->library('grocery_CRUD');
$this->load->model('Project_list_model');
}
public function boq_doc(){
$crud = new grocery_CRUD();
// set datatable theme
$crud->set_theme('datatables');
//set the table name
$crud->set_table('staff');
$crud->columns('item_no','description');
$id = $this->uri->segment(3);
$data['single_boq'] = $this->project_list_model->show_boq_id($id);
//view output
$output = $crud->render();
$this->_example_output($output);
}
// edit /view /delete plan
public function boq_doc1()
{
// load plan
$this->grocery_crud->set_table('boq');
$output = $this->grocery_crud->render();
$this->_example_output($output);
}
// _example_output
function _example_output($output = null)
{
//load edit /view /delete plan
$this->load->view('our_template.php',$output);
}
// /._example_output
}

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; ?>
..
}

Resources