Get value from joined tables, Codeigniter - codeigniter

I'm trying to get and display the data from joined tables but I can't get anything in return. I reference this and it worked on my other function, but when I tried it again on a different function, I can't get any results.
Here's the Model:
public function viewReview($id)
{
$this->db->select('clients.firstname, clients.lastname, packages.title, rate_review.review, rate_review.date_created');
$this->db->where('rate_review.id', $id);
$this->db->join('clients', 'clients.id = rate_review.user_id');
$this->db->join('packages', 'rate_review.package_id = packages.id');
$this->db->from('rate_review');
$query = $this->db->get();
return $query->row_array();
}
Controller:
public function view_review($id)
{
$data['title'] = 'Rate & Reviews';
$data['review'] = $this->Admin_model->viewReview($id);
$this->load->view('../admin/template/admin_header');
$this->load->view('../admin/template/admin_topnav');
$this->load->view('../admin/template/admin_sidebar');
$this->load->view('../admin/rate_review/view', $data);
$this->load->view('../admin/template/admin_footer');
}
View:
<div class="card-body">
<p>User:
<?php echo $review['firstname'].' '. $review['lastname']; ?>
</p>
<p>Package:
<?php echo $review['title']; ?>
</p>
<div class="m-2">
<pre class="border-2"><?php echo $review['review']; ?></pre>
<br>
<span class="mt-2"><?php echo $review['date_created']; ?></span>
</div>
</div>
When I var_dump($query) in model, this is what I get

the query seems to be fine except that we do not know if the data really exists in those joined tables. Are you sure data if there? the best way to debug is to use profiler so that you preview the real query built $this->output->enable_profiler(TRUE), after that take that query and run it on the mysql directly.
place this anywhere in your controller $this->output->enable_profiler(TRUE).

Please be sure the path is correct and try this query in your model
public function viewReview($data) {
$sql = "SELECT c.firstname as firstname, c.lastname as lastname, p.title as title, r.review as review, r.date_created as date_created FROM rate_review r INNER JOIN clients c ON (c.id = r.user_id)
INNER JOIN packages p ON (p.id = r. package_id) WHERE r.id = ?";
$query = $this->db->query($sql, $data);
return (array)$query->row();
}
Also please change this line in your controller
$data['review'] = $this->Admin_model->viewReview(array($id));
Then error log what you get please
error_log($data['review']);

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.

Joomla Virtuemar 2.x

im traying to show in the products detail page, the list of the other products by the same Manufacturer. I mean, if you are in a Shoes from Adidas, the page shows up the another adidas products. So i have this code:
http://codepad.org/pO8XF0OI (Dont Know how to write code here)
Is actually working but only shows the products by the Category no by the Manufacturer.
What i'm doing wrong?
Try this,
If you are using Vm2.x It will gives you full products under one manufacture.You can add or remove another tables based on your requirement.
$db = &JFactory::getDBO();
$sql = "SELECT N.product_name,M.virtuemart_product_id,MN.mf_name
FROM jos_virtuemart_product_manufacturers AS M
LEFT JOIN jos_virtuemart_products AS P ON M.virtuemart_product_id = P.virtuemart_product_id
LEFT JOIN jos_virtuemart_products_en_gb AS N ON N.virtuemart_product_id = M.virtuemart_product_id
LEFT JOIN jos_virtuemart_manufacturers_en_gb AS MN ON MN.virtuemart_manufacturer_id = M.virtuemart_manufacturer_id
WHERE M.virtuemart_manufacturer_id = '$manufature_id'";
$db->setQuery($sql);
$db->query();
$res = $db->loadAssocList();
echo "<pre/>";
print_r($res);
Hope this may help...
Is done, here is the code:
<?php
$db = &JFactory::getDBO();
$manufacturer = $this->product->virtuemart_manufacturer_id;
$sql = "SELECT N.product_name,I.virtuemart_media_id,M.virtuemart_product_id,MN.mf_name
FROM h3ls8_virtuemart_product_manufacturers AS M
LEFT JOIN h3ls8_virtuemart_products AS P ON M.virtuemart_product_id = P.virtuemart_product_id
LEFT JOIN h3ls8_virtuemart_products_es_es AS N ON N.virtuemart_product_id = M.virtuemart_product_id
LEFT JOIN h3ls8_virtuemart_product_medias AS I ON M.virtuemart_product_id = I.virtuemart_product_id
LEFT JOIN h3ls8_virtuemart_manufacturers_es_es AS MN ON MN.virtuemart_manufacturer_id = M.virtuemart_manufacturer_id
WHERE M.virtuemart_manufacturer_id = '$manufacturer'"; // h3ls8_ is your table Prefix
$db->setQuery($sql);
$db->query();
/* $res = $db->loadAssocList(); //This Load the info as a List */
$prod = $db->loadObjectList(); // This Load the info as a group of objects for loading it.
JRequest::setVar('virtuemart_manufacturer_id',$this->product->virtuemart_manufacturer_id,'GET');
$productModel = VmModel::getModel('product');
if ($this->product->virtuemart_manufacturer_id !=0 ) {
$products = $prod;
$productModel->addImages($products);
$this->assignRef('products', $products);
}
// Show Products
if (!empty($products)) { ?>
<div class="seven columns obras">
<h5> Obras </h5>
<div class="row">
<?php
// Start the Output
foreach ($products as $product) {
// Show Products
?>
<div class="four columns mobile-two end producto">
<div class="imagen">
<!-- <?php //if ($product->product_special == 1) { ?>
<div class="oferta">
<br />
</div>
<?php}?> *** If you wanna add some especial icon to a Special product uncommnent this *** -->
<?php
echo JHTML::_('link', JRoute::_('index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id='.$product->virtuemart_product_id.'&virtuemart_category_id='.$product->virtuemart_category_id),$product->images[0]->displayMediaThumb('class="catImage"',false));
?>
</div>
</div> <!-- end of product -->
<?php } ?>
</div>
</div>
<?php } ?>

errors in code noob cant fix them [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am working on a small application that displays data from a database table. I am getting 2 errors and dont know why are there, and I cant figure it out as I am still a noob. I guess its something stupid, please help.
ERRORS
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: querys
Severity: Warning
Message: Invalid argument supplied for foreach()
these errors are located in my view page.
VIEW
<?php foreach ($queries as $row): ?>
<table>
<th>Name</th>
<th>Surname</th>
<th>phone</th>
<th>email</th>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->surname; ?></td>
<td><?php echo $row->phone; ?></td>
<td><?php echo $row->email; ?></td>
</table>
<?php endforeach; ?>
CONTROLLER
function display($offset = 0)
{
$limit = 20;
$this->load->model('info_model');
$results = $this->info_model->search($limit, $offset);
$data['queries'] = $results['rows'];
$data['num_results'] = $results['num_rows'];
$this->load->view('info_view',$data);
}
MODEL
function search ($limit, $offset){
//results query
$q = $this->db->select('ID, name, surname, phone, email');
$this->db->from('tblinfo');
$this->db->limit($limit, $offset);
$ret['rows'] = $q->get()->result();
//count query
$q = $this->db->select('COUNT(*) as count', FALSE )
->from('tblinfo');
$tmp = $q->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}
EDIT
i fixed the foreach error by inserting
<?php if(is_array($queries)): ?>
<?php endif; ?>
the only error i am getting is the
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: queries
$data['query'] = $results['rows'];
should be
$data['querys'] = $results['rows']; // although correct spelling is "queries"
Then you can access $querys inside your view.
The problem seems to be with your models search() method, which is probably not returning any results. I would re-write it as follows to utilize codeigniters active record class:
function search ($limit, $offset){
//results query
$this->db->select('ID, name, surname, phone, email');
$q = $this->db->get('tblinfo', $limit, $offset);
$ret['rows'] = $q->result();
//count query
$ret['num_rows'] = $this->db->count_all('tblinfo');
return $ret;
}
You can use Codeigniters active record class to get a count of all records in a specific table using just $this->db->count_all('table_name');
Personally I think a function should perform only one task. Right now you are trying to do two tasks (return records and return a record count) in one function.
I would rewrite my model like this:
function search($limit, $offset)
{
$this->db->select('ID, name, surname, phone, email');
$this->db->from('tblinfo');
$this->db->limit($limit, $offset);
return $this->db->get();
}
And your controller could look like this:
function display($offset = 0)
{
$this->load->model('info_model');
$results = $this->info_model->search(20, $offset);
$data['queries'] = $results->result();
$data['num_results'] = $this->db->count_all('tblinfo'); // Alternatively you could make a separate model function that does this
$this->load->view('info_view', $data);
}
Maybe change your search code a little
$q = $this->db->select('ID, name, surname, phone, email')
->from('tblinfo')
->limit($limit, $offset);
Change your model code to this
function search ($limit, $offset){
//results query
$this->db->select('ID, name, surname, phone, email');
$this->db->from('tblinfo');
$this->db->limit($limit, $offset);
$q = $this->db->get();
$ret['rows'] = $q->result();
//count query
$q1 = $this->db->select('COUNT(*) as count', FALSE )
->from('tblinfo');
$tmp = $q1->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}

Codeigniter pagination with my own query

first be gentle im a begginer.
I have a problem with codeogniter pagination and im totally clules.
I watched a lot of tuts on the net and never got any aswer.
My problem is, im building a real-estate site, it has 2 types of estate, for sale and for rent.
My query looks like this
function for_sale()
{
$query = $this->db->query(" SELECT city, rand_id, price, image FROM estate WHERE type = 'for_sale' ");
if ($query->num_rows() > 0)
{
foreach ($query->result() as $f)
{
$for_sale[] = $f;
}
return $for_sale;
}
}
my controller
function index()
{
$this->load->view("header");
$this->load->model('estate_model');
$for_sale['result'] = $this->estate_model->for_sale();
$this->load->library('pagination');
$config['base_url'] = 'http://localhost/kpi/for_sale/index';
$config['total_rows'] = 22;
$config['per_page'] = 9;
$config['num_links'] = 19;
$this->pagination->initialize($config);
// $data['records'] = $this->db->get('ingatlan', $config['per_page'], $this->uri->segment(3));
$this->load->view("for_sale_view", $for_sale);
$this->load->view("footer");
}
and my view
foreach($results as $r) {
echo '<div class="grid_4">';
echo '<p class="title">Estate for sale</p>';
echo '<div class="thumbnail">
<div class="info">
<p class="bar">'.$r->city.'</p>
<p></p>
</div>
'.$r->image.'</div>';
echo '<div class="more">View details</div>';
echo '</div>';
}
So my problem is i cant figure this out how to use it with my query, i watched lots of tuts, that i need to load in the table library, and pass a data array like this
$data['records'] = $this->db->get('estate', $config['per_page'], $this->uri->segment(3));
anf give the per page this result `$this->db->get('estate')->num_rows(); but i would like this with my query, and not with a table.
So can someone hive me a hint?
Thank you
... i need to load in the table library, and pass a data array ...
how you display your data is totally up to you. the html-table class can help you with that, but it is not necessary to use it. your view should work just fine except for the fact that you want to iterate over $results which will be empty because you put your data into $for_sale['result'] (results != result).
in order for the pagination library to work with your query, you have to pass your query 2 parameters:
how many rows/records should be loaded from your db (= $config['per_page'])
how many rows/records should be skipped at the beginning (also known as 'offset', this value will be provided by the pagination library = $this->uri->segment(3))
So instead of:
$for_sale['result'] = $this->estate_model->for_sale();
Model:
function for_sale()
{
$query = $this->db->query(" SELECT city, rand_id, price, image FROM estate WHERE type = 'for_sale' ");
...
}
you should try:
$for_sale['result'] = $this->estate_model->for_sale($config['per_page'],$this->uri->segment(3));
Model:
function for_sale($per_page, $offset) {
$query = $this->db->query(" SELECT city, rand_id, price, image FROM estate WHERE type = 'for_sale' LIMIT $offset, $per_page");
...
return $query->result();
}
One last thing: the pagination library has to be initialized BEFORE you query the database.
And another last thing: $config['total_rows'] = 22; you will probably want to replace that with something like $this->estate_model->get_for_sale_total_rows()
Hope this helps.

in one foreach call second foreach! codeigniter

hier is the problem:
in codeigniter in controller I have next code:
$query_not_voted = "SELECT * FROM photos WHERE p_id NOT IN (SELECT distinct p_id FROM p_votes where u_id = ".$this->session->userdata('u_id').") LIMIT ".$this->db->escape_str($segment_url).", ".$config['per_page'];
$q = $this->db->query($query_not_voted);
$data['myphotos'] = $q->result_array();
foreach($data['myphotos'] as $key=>$val)
{
$query_g = "SELECT * FROM users WHERE u_id = (SELECT u_id FROM p_votes WHERE p_id = ".$val['p_id'].")";
$q_2 = $this->db->query($query_g);
$data['allvotess'] = $q_2->result_array();
$query_u = "SELECT * FROM users WHERE u_id = ".$val['u_id']." LIMIT 0, 5";
$q_1 = $this->db->query($query_u);
$data['author'] = $q_1->result_array();
}
So now I have $data['myphotos'] and this is can be outputted in view with next codes:
<?php foreach ($myphotos as $keys => $myphoto){ ?>
<div id="voteblock">
<div id="voteleft">
<img src="<?php echo base_url().$myphoto['p_thumb']; ?>" />
</div>
<?php } ?>
but how can I output $data['allvotess'] in last foreach loop?
I tried to do same, but didn't work out.
Then I tried to push the results inside $data['myphotos'] and no good result!
So What I'm Doing???
Just need someone to help me with foreachloop insite foreachloop!!!
For a week I just can't do, I can even pay for solution right now!!!
I posted also at codeingiter forum, but they say it's easy hier is link
Generally in views I use the more semantic way to write foreach and if statements, and I'll also illustrate a tiered foreach loop...
$array1 = array(1,2,3,4);
$array2 = array(1,2,3,4);
$array3 = array(1,2,3,4);
$second_array[] = $array1;
$second_array[] = $array2;
$second_array[] = $array3;
so now we have $second_array that is a multi-dimensional array...
$data->second_array = $second_array;
$this->load->view('your/view',$data);
in a view file...
<? foreach($second_array as $array): ?> //<--start first foreach loop
<div>do some stuff</div>
<? foreach($array as $array_item): ?> //<--start second foreach loop, inside the first
<div>do some other stuff for every item in $array</div>
<? endforeach; ?> //<--end first foreach
<? endforeach; ?> //<--end second foreach

Resources