I will start from very beginning, I am creating small CMS with code igniter and I faced with few problems. I am junior in working with php frameworks, so please do not be angry at me.
Right now I have vehicles models lists from database and that one is large. So I got Error from CodeIgniter:
A PHP Error was encountered
Severity: Error
Message: Allowed memory size of
At this moment I'm already commented the line of code from code igniter output configuration file, which shows me this error. And I have a clear list of values, that I want to have. But its too many. So I thought about PAGINATION.
What its your opinion, can it help me? maybe you have some better advice/suggestion?
So I tried to turn that error down and create a pagination, but I failed.
This is my controller if "lists":
public function lists(){
//get models
$data['models'] = $this->Model_model->get_models('id', 'DESC');
//get brands
$data['brands'] = $this->Model_model->get_brands('id', 'DESC');
//get brands
$data['brand'] = $this->Model_model->get_brands('id', 'DESC');
//get categories
$data['categories'] = $this->Model_model->get_categories('id', 'DESC');
//get Users
//$data['users'] = $this->User_model->get_users('id', 'DESC', 5);
//View
$data['main_content'] = 'admin/models/lists';
$this->load->view('admin/layouts/main', $data);
}
This is code from model file:
<?php
class Model_model extends CI_Model
{
/*
* Get vehicle models
*
* #param - $order_by (string)
* #param - $sort (string)
* #param - $limit (int)
* #param - $offset (int)
*
* */
public function get_models($order_by = null, $sort = 'DESC', $limit = null, $offset = 0)
{
$this->db->select('vm.*, vb.v_brand_name as v_brand_name, vc.category_name as category_name, u.first_name, u.last_name');
$this->db->from('vehicle_models as vm');
$this->db->join('vehicle_brands as vb', 'vb.id = vm.vehicle_brand_id');
$this->db->join('vehicle_category as vc', 'vc.id = vb.vehicle_category_id', 'vb.vehicle_category_id = vm.vehicle_category_id', 'left');
$this->db->join('users as u', 'u.id = vb.user_id', 'left');
if ($limit != null) {
$this->db->limit($limit, $offset);
}
if ($order_by != null) {
$this->db->order_by($order_by, $sort);
}
$query = $this->db->get();
return $query->result();
}
/*
*
*Get Menu Items
*
* */
/* public function get_models(){
$this->db->where('id', 1);
$this->db->order_by('id');
$query = $this->db->get('vehicle_models');
return $query->result;
}*/
/*
*GET SINGLE ARTICLE
* */
public function get_model($id)
{
$this->db->where('id', $id);
$query = $this->db->get('vehicle_models');
return $query->row();
}
/*
* Get vehicle Categories
*
* #param - $order_by (string)
* #param - $sort (string)
* #param - $limit (int)
* #param - $offset (int)
*
* */
public function get_categories($order_by = null, $sort = 'DESC', $limit = null, $offset = 0)
{
$this->db->select('*');
$this->db->from('vehicle_category');
if ($limit != null) {
$this->db->limit($limit, $offset);
}
if ($order_by != null) {
$this->db->order_by($order_by, $sort);
}
$query = $this->db->get();
return $query->result();
}
/*
* Get vehicle Brands
*
* #param - $order_by (string)
* #param - $sort (string)
* #param - $limit (int)
* #param - $offset (int)
*
* */
public function get_brands($order_by = null, $sort = 'DESC', $limit = null, $offset = 0)
{
$this->db->select('*');
$this->db->from('vehicle_brands');
if ($limit != null) {
$this->db->limit($limit, $offset);
}
if ($order_by != null) {
$this->db->order_by($order_by, $sort);
}
$query = $this->db->get();
return $query->result();
}
/*
*
*Insert Model
*
* */
public function insert($data){
$this->db->insert('vehicle_models', $data);
return true;
}
/*public function insert_models($data){
$models = implode(',',$_POST['v_model_name']);
$this->db->insert('vehicle_models', $data);
$this->db->into('vehicle_models', $data);
$this->db->values($model);
}*/
public function update($data, $id){
$this->db->where('id', $id);
$this->db->update('vehicle_models', $data);
return true;
}
public function did_delete_row($id){
$this -> db -> where('id', $id);
$this -> db -> delete('vehicle_models');
return true;
}
/* --------------------------- PAGINATION ---------------------------------*/
public function __construct() {
parent::__construct();
}
public function record_count() {
return $this->db->count_all("vehicle_models");
}
public function fetch_countries($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get("vehicle_models");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
/*-------------------------- AND OF PAGINATION ---------------------------------------*/
}
And this is my view file:
<?php foreach($categories as $category) :?>
<?php
$this->load->helper("url"); /
$postid = $this->uri->segment(4);
if ($category->id == $postid):
?>
<!-- ************************* ****************************************-->
<div class="table-responsive col-md-12">
<h2><?php echo $category->category_name; ?></h2>
<table class="table table-striped">
<thead>
<tr>
<th>Model (+View)</th>
<th>Brand</th>
<th>Category</th>
<th></th>
<th>Moves</th>
</tr>
</thead>
<tbody>
<?php foreach ($models as $model) : ?>
<?php if($model->vehicle_category_id == $postid) :?> <!-
<tr>
<td>
<?php echo $model->v_model_name; ?>
</td>
<?php foreach($brands as $brand) :?><?php if($model->vehicle_brand_id == $brand->id) :?>
<td>
<?php echo $brand->v_brand_name; ?>
</td>
<?php endif; ?>
<?php endforeach; ?>
<td>
<?php echo $model->category_name; ?>
</td>
<td>
</td>
<td>
Edit
Delete
</td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</tbody>
</table>
</div>
<!-- ************************* ****************************************-->
<?php endif;?>
<?php endforeach; ?>
** MORE QUESTIONS**
So maybe somebody can help me to create PAGINATION?
I tried to put this code to "list" controller function but its didnt
work:
public function lists1(){
$this->load->library('pagination');
$config['base_url'] = 'http://localhost/test/admin/Models/lists/';
$config['per_page'] = 5;
$config['num_links'] = 5;
$config['total_rows'] = $this->db->get('vehicle_models')->num_rows();
/*$config['total_rows'] = $this->db->get_models('v_model_name');*/
$this->pagination->initialize($config);
$data['query'] = $this->db->get('vehicle_models', $config['per_page'],$this->uri->segment(4)); /*segment*/
$this->load->view('admin/models/lists', $data); /*nuoroda*/
echo $this->pagination->create_links();
$data['main_content'] = 'admin/models/lists';
$this->load->view('admin/layouts/main', $data);
Will pagination will help me to deal with to many list items?
Maybe somebody can help me with code? Thanks.
Your codeigniter code is storing the entire list in array first. After that you are trying to build the screen. Perhaps you can start with a SQL join and use limit in that join to restrict the number of rows. Also, send your script page number for pagination.
<?php
$current = $_GET['page'];
$rowCount = $_GET['length'];
$sql = "select * from model m
inner join brand b
on m.vehicle_brand_id = b.id
limit ".($current - 1)*($rowCount).",".$rowCount;
$query = $this->db->query($sql);
$content['tableList'] = $query->result();
In this way, you will not pull entire data, which eventually causes memory exhaustion error.
Related
Using Codeigniter 3, I would like to display all the records from a table in a MySQL database. I'd also like to include the number of records selected.
For example;
Showing x number of records;
record 1
record 2
record 3
etc
Currently I have the following (which works);
// select all records
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
// count all records
public function countRecords() {
$this->db->select('count(*) as count');
$this->db->from('records');
$query = $this->db->get();
return $query->row();
}
My question is do I need two separate queries in order to achieve this (select and count)?
Is there a more efficient way of achieving what I want?
You can do something like this :
public function selectRecords()
{
$query = $this->db->get('records');
if ($query->num_rows() > 0 )
{
$records = $query->result_array();
$data['count'] = count($records);
$data['all_records'] = $records;
return $data;
}
}
Pass it to the view from your controller :
$data = $this->model_name->selectRecords();
/*print_r($data) to see the output*/
$this->load->view('your_view',$data);
In view :
<?php echo $count .' number of records';?>
you can do only:
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
and
$records = $this->selectRecords();
$count = count($records);
In The first function itself you can get the count using $query->num_rows() function
public function selectRecords() {
$return = array();
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
$return['count'] = $query->num_rows();
$return['records'] = $query->result_array();
return $return;
}
try this
it will help you to provide pagination for records
public function selectRecords($params = array(), $count = false) {
$offset = isset($params['offset']) ? $params['offset'] : '';
$limit = isset($params['limit']) ? $params['limit'] : '';
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
if ($count) {
return $this->db->get()->num_rows();
}
if (empty($offset) && !empty($limit)) {
$this->db->limit($limit);
}
if (!empty($offset) && !empty($limit)) {
$this->db->limit($limit, $offset);
}
$result = $this->db->get()->result();
return $result;
}
So, I have been trying to get this delete function to work now for a while.
At the bottom of the foreach I have a delete function. The funtion itself does work, however it always selects the post id of 1.
View
<div><?php foreach($posts as $post) : ?>
<hr>
<h3><?php echo $post['title']; ?></h3>
<div class="row">
<div class="col-md-3">
<img class="post-thumb" src="<?php echo site_url(); ?>posts/image/<?php echo $post['post_image']; ?>">
</div>
<div class="col-md-9">
<small class="post-date">Posted on: <?php echo $post['created_at']; ?> in <strong><?php echo $post['name']; ?></strong></small><br>
<?php echo word_limiter($post['body'], 60); ?>
<br><br>
<p><a class="btn btn-default" href="<?php echo site_url('/posts/'.$post['slug']); ?>">Read More</a></p>
</div>
</div>
<?php echo form_open('/posts/delete/'.$post['id']); ?>
<input type="submit" value="Delete" class="btn btn-danger">
</form>
Controller
public function posts($offset = 0){
// Pagination Config
$config['base_url'] = base_url() . 'admins/posts/';
$config['total_rows'] = $this->db->count_all('posts');
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['attributes'] = array('class' => 'pagination-link');
// Init Pagination
$this->pagination->initialize($config);
$data['title'] = 'Latest Posts';
$data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);
$this->load->view('templates/header');
$this->load->view('admins/posts', $data);
$this->load->view('templates/footer');
}
Model
public function delete_post($id){
$image_file_name = $this->db->select('post_image')->get_where('posts', array('id' => $id))->row()->post_image;
$cwd = getcwd(); // save the current working directory
$image_file_path = $cwd."\\assets\\images\\posts\\";
chdir($image_file_path);
unlink($image_file_name);
chdir($cwd); // Restore the previous working directory
$this->db->where('id', $id);
$this->db->delete('posts');
return true;
}
EDIT:
get_posts in model
public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
if($limit){
$this->db->limit($limit, $offset);
}
if($slug === FALSE){
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'categories.id = posts.category_id');
$query = $this->db->get('posts');
return $query->result_array();
}
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->row_array();
}
The function does run and I get a confirmation message, so the only thing I am really confused about is the Id.
The whole thing is written using the CodeIgniter Framework.
Check your get_post model properly. From what you have, it looks like your query will get it's id from the category table.
Try this instead
public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
if($limit){
$this->db->limit($limit, $offset);
}
if($slug === FALSE){
$this->db->select('posts.id AS id, posts.slug, posts.body, posts.created_at');
$this->db->from('posts, categories');
$this->db->where('categories.id = posts.category_id');
$query = $this->db->get();
return $query->result_array();
}
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->result_array();
}
Updating your join to LEFT JOIN or simple use WHERE
you are returning only 1 line with row_array() function so you should replace for result_array():
public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
if($limit){
$this->db->limit($limit, $offset);
}
if($slug === FALSE){
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'categories.id = posts.category_id');
$query = $this->db->get('posts');
return $query->result_array();
}else{
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->result_array();
}
}
Thanks to everyone, your answers helped me a lot and I learned a few new things about PHP. I tried implementing your Ideas and they solved the area of the problem I was asking about. In the end I decided to use a simple mysqli query to get the data I needed from the database. mysqli_query($con, "SELECT id,category_id,user_id,title,body,created_at FROM posts Order By id DESC");
May be i am wrong but i think its a foreach syntax issue,
because if you getting same id in all the
rows,
you need to write like,
<?php foreach ($posts as $post) : ?>
instead of,
<?php foreach ($posts as $post) { ?>
//your code goes here
<?php } ?>
I'm trying to connect from Prestashop to external database (ERP) to get the order history from it.
I've cloned the History controller and named it "residui".
I've created ResiduiController.php that contains:
class ResiduiControllerCore extends FrontController {
public $auth = true;
public $php_self = 'residui';
public $authRedirection = 'residui';
public $ssl = true;
public function setMedia() {
parent::setMedia();
$this->addCSS(array(
_THEME_CSS_DIR_.'residui.css',
));
$this->addJS(array(
_THEME_JS_DIR_.'history.js',
_THEME_JS_DIR_.'tools.js' // retro compat themes 1.5
));
$this->addJqueryPlugin('footable');
$this->addJqueryPlugin('footable-sort');
$this->addJqueryPlugin('scrollTo'); }
public function initContent() {
parent::initContent();
$residui = Order::getCustomerResidui($this->context->customer->id);
$this->context->smarty->assign(array(
'residui' => $residui
));
$this->setTemplate(_PS_THEME_DIR_.'residui.tpl'); } }
I've inserted the class getCustomerResidui in Order.php:
public static function getCustomerResidui($id_customer, $showHiddenStatus = false, Context $context = null) {
if (!$context)
$context = Context::getContext();
$evadi = 'S';
$stato = 'GENERATO';
$resi = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_PREFIX_."tesbro
WHERE id_cli_presta = '".(int)$id_customer."' AND status = '".$stato."'
ORDER BY id_tes DESC");
if (!$resi)
return array();
foreach ($resi as $key => $val) {
$resi2 = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_PREFIX_."rigbro
WHERE id_doc = '".$val['numdoc']."' AND evadi <> '".$evadi."'
ORDER BY codart DESC LIMIT 1");
if ($resi2)
$resi[$key] = array_merge($resi[$key], $resi2[0]); }
return $resi; } }
I've added the getFromGazie instance in DB.php and all connection parameters to the external DB in settings.inc.php, such as GAZ_PREFIX, etc.
DB.php:
public static function getFromGazie($master = true) {
static $id = 0;
// This MUST not be declared with the class members because some defines (like _DB_SERVER_) may not exist yet (the constructor can be called directly with params)
if (!self::$_servers)
self::$_servers = array(
array('gaz_server' => _GAZ_SERVER_, 'gaz_user' => _GAZ_USER_, 'gaz_password' => _GAZ_PASSWD_, 'gaz_database' => _GAZ_NAME_), /* MySQL Master server */
);
Db::loadSlaveServers();
$total_servers = count(self::$_servers);
if ($master || $total_servers == 1)
$id_server = 0;
else {
$id++;
$id_server = ($total_servers > 2 && ($id % $total_servers) != 0) ? $id % $total_servers : 1; }
if (!isset(self::$instance[$id_server])) {
$class = Db::getClass();
self::$instance[$id_server] = new $class(
self::$_servers[$id_server]['gaz_server'],
self::$_servers[$id_server]['gaz_user'],
self::$_servers[$id_server]['gaz_password'],
self::$_servers[$id_server]['gaz_database']); }
return self::$instance[$id_server]; }
The template, residui.tpl:
<div class="block-center" id="block-history">
<table id="order-list" class="table table-bordered footab">
<thead>
<tr>
<th class="first_item" data-sort-ignore="true">{l s='Order reference'}</th>
<th class="item">{l s='Date'}</th>
</tr>
</thead>
<tbody>
{foreach from=$residui item=residuo name=myLoop}
<tr class="{if $smarty.foreach.myLoop.first}first_item{elseif $smarty.foreach.myLoop.last}last_item{else}item{/if} {if $smarty.foreach.myLoop.index % 2}alternate_item{/if}">
<td class="history_link bold">
<p class="color-myaccount">
{$residuo['numdoc']}
</p>
</td>
<td class="history_date bold">
{$residuo['datemi']}
</td>
</tr>
{/foreach}
</tbody>
</table>
<div id="block-order-detail" class="unvisible"> </div>
The problem is that I don't get any line displayed (I also tested the query manually in PhpMyAdmin).
I tried for hours but I can't see the mistake (and I'm sure I did one or more).
Can you tell me something? Thanks...
Got it!!!!
First of all thanks to Sergii P that suggests me _PS_MODE_DEV_ that I didn't know...
The problem was that it was always trying to execute the query on the same DB. To solve that, i added _GAZ_NAME_ before _GAZ_PREFIX_, like this:
public static function getCustomerResidui($id_customer, $showHiddenStatus = false, Context $context = null)
{
if (!$context)
$context = Context::getContext();
$evadi = 'S';
$stato = 'GENERATO';
$resi = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_NAME_."."._GAZ_PREFIX_."tesbro
WHERE id_cli_presta = '".(int)$id_customer."' AND status = '".$stato."'
ORDER BY id_tes DESC");
if (!$resi)
return array();
foreach ($resi as $key => $val)
{
$resi2 = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_NAME_."."._GAZ_PREFIX_."rigbro
WHERE id_doc = '".$val['numdoc']."' AND evadi <> '".$evadi."'
ORDER BY codart DESC LIMIT 1");
if ($resi2)
$resi[$key] = array_merge($resi[$key], $resi2[0]);
}
return $resi;
}
Et voilĂ , everything works fine!
I am new at codeigniter. I have a problem with codeigniter's pagination.
I tried to search google, youtube and codeigniter documentation but I didn't find anything.
I can implement a simple pagination but I need to create multi pagination with a database in one table.
Anyone that can help me please?
My database:
product:
id category title image
1 burger a a.jpg
2 burger b b.jpg
3 burger c c.jpg
4 pizza d d.jpg
5 pizza e e.jpg
6 pizza f f.jpg
The result that I want is pagination in one page
(pagination category burger by burger,pizza by pizza)
and my url is http://localhost/test-ci1/
Code in Model:
<?php
class Product_model extends CI_Model {
function get_burgers($category="", $limit, $start) {
$this->db->select('*');
$this->db->from('product');
if($category) {
$this->db->where('category',$category);
}
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query->result();
}
function get_total($category="") {
$this->db->select('count(*) AS num_row');
$this->db->from('product');
if($category) {
$this->db->where('category',$category);
}
$this->db->limit(1);
$query = $this->db->get();
return $query->row()->num_row;
}
}
in the Controller:
<?php
class Site extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('product_model','product');
}
public function index()
{
$this->load->model('Product_model');
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data = array();
$per_page =2;
$data["pizza"] = $this->product->get_burgers('pizza', $per_page, $page);
$total_pizza = $this->product->get_total('pizza');
$limit= 2;
$link_pizza = 'http://localhost/test-ci1/pizza';
$data['pagination_pizza'] = $this->pagination($total_pizza,$limit,$link_pizza);
$data["burgers"] = $this->product->get_burgers('burger', $per_page, $page);
$total_burger = $this->product->get_total('burger');
$limit = 2;
$link_burger = 'http://localhost/test-ci1/index/burger';
$data['pagination_burger'] = $this->pagination($total_burger,$limit,$link_burger);
$this->load->view('home_page_view',$data);
}
private function pagination($total ,$per_page ,$link) {
$config['base_url'] = $link;
$config['total_rows'] = $total;
$config['per_page'] = $per_page;
$config['page_query_string'] = TRUE;
$this->pagination->initialize($config);
return $this->pagination->create_links();
}
}
and in my View:
<body>
<h1>Pizza</h1>
<ul>
<?php foreach($pizza as $val) { ?>
<li><?php echo $val->title; ?></li>
<?php } ?>
</ul>
<?php echo $pagination_pizza; ?>
<hr>
<h1>Burger</h1>
<ul>
<?php foreach($burgers as $val) { ?>
<li><?php echo $val->title; ?></li>
<?php } ?>
</ul>
<?php echo $pagination_burger; ?>
</body>
and my result:
Pizza
pizza1
burger2
12>
Burger
burger1
assasa
12>
As I can see you haven't developed your model pagination. You should add a function that does the pagination for you while extracting only the wanted rows from the database.
For your example something like this in your model will do:
function get_burgers($category="", $limit, $start) {
$this->db->select('*');
$this->db->from('product');
if($category) {
$this->db->where('category',$category);
}
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query->result();
}
And in your controller instead of fetching just one burger you should
$data["burgers"] = $this->burger_model->get_burgers($category, $config["per_page"], $page);
And change your foreach in your view to iterate through the burgers
Can anyone explain why I cannot get a variable called $siteID to pass to another function within the same controller?
In the third function called "get_orders_by_site" I have loaded a different model, which returns information about 'orders' raised at the currently viewed building/site/property.
The sites controller works perfectly, first function lists a table with all my properties, then when one is clicked - the second function gets the siteID of that selection, and returns with further 'detail/data' - sites controller function1/2 all relate to the same model, and return information from the SAME table.
I'm trying to implement a third function, which will do a similar task, but return with information/data from a different table (the site.siteID, is also a FK in the orders.siteID table i've created in phpmyadmin).
If I need to explain further please let me know - Many thanks!
amended code
Sites Controller
<?php
class Sites extends CI_Controller {
//Searches for a list of sites
public function search($sort_by = 'site_title', $sort_order = 'asc', $offset = 0)
{
$limit = 20;
$data['columns'] = array(
'site_title' => 'Site Name',
'site_uprn' => 'Unique Property Reference'
);
$this->load->model('site_model');
$results = $this->site_model->get_sites($limit, $offset, $sort_by, $sort_order);
$data['sites'] = $results['rows'];
$data['num_results'] = $results['num_rows'];
//pagination for list returned
$this->load->library('pagination');
$config = array ();
$config['base_url'] = site_url("Sites/search/$sort_by/$sort_order");
$config['total_rows'] = $data['num_results'];
$config['per_page'] = $limit;
$config['uri_segment'] = 5;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$data['sort_by'] = $sort_by;
$data['sort_order'] = $sort_order;
$this->load->view('search', $data);
}
//Displays individual site details
//passes selected siteID to the model, and returns only database/info for that particular building/property
public function details($siteID){
$this->load->model('site_model');
$data['site']=$this->site_model->get_site($siteID);
$this->load->view('site', $data);
$this->load->view('orders', $data);
}
// this second function should do a similar method as above, however I've loaded a different model, as i'm getting information from a different database table - but I still want the data returned to be limited by the building/site ID which the user selects.
public function orders_by_site($siteID, $sort_by = 'orderID', $sort_order = 'asc', $offset = 0)
{
$this->load->model('site_model');
$this->load->model('order_model');
$limit = 20;
$data['columns'] = array(
'orderID' => 'Order No.',
'initiated_date' => 'Initiated Date',
'target_date' => 'Target Date',
'status' => 'Status',
'priority' => 'Priority',
'trade_type' => 'Trade Type'
);
$results = $this->site_model->get_site($siteID);
$results = $this->order_model->get_orders($siteID, $limit, $offset, $sort_by, $sort_order);
$data['orders'] = $results['rows'];
$data['num_results'] = $results['num_rows'];
//pagination for orders table
$this->load->library('pagination');
$config = array ();
$config['base_url'] = site_url("Orders/orders_by_site/$sort_by/$sort_order");
$config['total_rows'] = $data['num_results'];
$config['per_page'] = $limit;
$config['uri_segment'] = 6;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$data['sort_by'] = $sort_by;
$data['sort_order'] = $sort_order;
$this->load->view('orders', $data);
}
}
End Sites Controller
Site Model
//Get all site data
function get_sites($limit, $offset, $sort_by, $sort_order){
$sort_order = ($sort_order == 'desc') ? 'desc' : 'asc';
$sort_columns = array('site_title', 'site_uprn');
$sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'site_title';
$q = $this->db->select('siteID, site_title, site_uprn')
->from('sites')
->limit($limit, $offset)
->order_by($sort_by, $sort_order);
$ret['rows'] = $q->get()->result();
//count query for sites
$q = $this->db->select('COUNT(*) as count', FALSE)
->from('sites');
$tmp = $q->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}
//Get individual site data
function get_site($siteID){
$this->db->select()->from('sites')->where(array('siteID' => $siteID));
$query = $this->db->get();
return $query->first_row('array');
}
}
Orders Model
//order table
function get_orders($siteID, $orderID, $limit, $offset, $sort_by, $sort_order){
$sort_order = ($sort_order == 'desc') ? 'desc' : 'asc';
$sort_columns = array('orderID', 'initiated_date', 'target_date','completion_date','status','priority','total_amount','job_description','requestor_name','requestor_telno','trade_type');
$sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'orderID';
$q = $this->db->select()->from('orders')->where(array('siteID' => $siteID))->limit($limit, $offset)->order_by($sort_by, $sort_order);
$ret['rows'] = $q->get()->result();
}
//order details
function get_order($orderID){
$this->db->select()->from('orders')->where(array('orderID' => $orderID));
$query = $this->db->get();
return $query->first_row('array');
}
}
Site View - only showing the extract where I'm trying to embed the orders view
<h5>Order Details</h5>
<?php include('orders.php')?>
</div>
</div>
</div>
Orders View
<div id="site_filter">
<div class="result_counter">
<h5>Found <?php echo $num_results; ?> Orders</h5>
</div>
<div class="pagination">
<?php if(strlen($pagination)): ?>
Page: <?php echo $pagination; ?>
<?php endif; ?>
</div>
</div>
<div class="clear_float"></div>
<table class="table">
<thead>
<?php foreach($columns as $column_name => $column_display): ?>
<th <?php if ($sort_by == $column_name) echo "class=\"sort_$sort_order\"" ?>>
<?php echo anchor("Sites/orders_by_site/$column_name/" .
(($sort_order == 'asc' && $sort_by == $column_name) ? 'desc' : 'asc') ,
$column_display); ?>
</th>
<?php endforeach; ?>
</thead>
<tbody>
<?php foreach($orders as $order): ?>
<tr>
<td><?php echo $order->orderID; ?></td>
<td><?php echo $order->initiated_date; ?></td>
<td><?php echo $order->target_date; ?></td>
<td><?php echo $order->status; ?></td>
<td><?php echo $order->priority; ?></td>
<td><?php echo $order->trade_type; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
OK, a couple of things here - and I'm gonna need some help
In the orders_by_site method, you're overwriting the results variable:
$results = $this->site_model->get_site($siteID);
$results = $this->order_model->get_orders($siteID, $limit, $offset, $sort_by, $sort_order);
Also, the way you're loading views is incorrect. You're loading your views like this:
$this->load->view('site', $data);
$this->load->view('orders', $data);
And what you need to be doing is this:
// you need to get the "contents" of the `orders` view in a variable
// and pass that to the `site` view
$data['orders'] = $this->load->view('orders', $data, TRUE);
$this->load->view('site', $data);
And change your site view to this:
<h5>Order Details</h5>
<?php echo $orders; ?>
</div>
</div>
</div>
I'm sure there's more going on than that, but that's all I can gather from what I've seen in your question and comments.
#swatkins -
Thank you very much for your help, you highlighted some issues I had overlooked - I've gone about this in a different fashion now.
Originally I was trying to use Active Record (i believe) to select data from one table, based on the selection of a record from a different table - and then pass this selection to another model and use it in a get_where statement.
I've managed to get this to work using the $this->uri->segment() method in my controller, and then passing this to the corresponding model.
Now I'm able to utilise the user selection of a 'building/propery' name, with it's address etc - and then I have a second model, which retrieves the 'orders/jobs' that have been raised at that building.