CI - Pass a variable from 1 controller to two models/views - php

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.

Related

Database returning an empty Array() in PHP Codeigniter

I want to return and join 4 tables and produce a table for my view in a codeigniter application but it is returning Array().And to display the records I am using a foreach loop in my view but unable to display the records.
I have tried to change the query but then it does not return the desired results.
This is the Controller Function :-
public function student_list()
{
// get Student list
$this->data['student_list'] = $student_list = $this->Teachers_Model-
>getStudentList($_SESSION['user_id']);
//$this->data['student_list'] = $this->Teachers_Model-
>getStudents($_SESSION['user_id']);
print_r($this->data['student_list']);
// get courses
$this->data['courses'] = $courses = $this->Courses_Model-
>getCourses(null, $_SESSION['user_id']);
$this->render('student_list/index');
}
This is the Model :-
public function getStudentList($teacher_uid, $student_list_id = null){
$this->db->select('teachers_student.*, students.student_uid,
courses.course_id, users.username');
$this->db->from('teachers_student');
$this->db->join('students', 'students.student_uid =
teachers_student.student_uid');
$this->db->join('courses', 'courses.id = teachers_student.course_id');
$this->db->join('users', 'users.id = teachers_student.student_uid');
if(!is_null($student_list_id)):
$where = array(
'teachers_student.id' => $student_list_id,
'teachers_student.status' => 1,
);
$this->db->where($where);
$query = $this->db->get();
$result = $query->row_array();
else:
$where = array(
'teachers_student.teacher_uid' => $teacher_uid,
'teachers_student.status' => 1,
);
$this->db->where($where);
$query = $this->db->get();
$result = $query->result_array();
endif;
return $result;
}
And this is the view :-
<?php
foreach ($student_list as $key => $item) {
?>
<tr role="row" class="odd">
<td class="sorting_1"><?= $item->student_uid; ?></td>
<td class="sorting_1"><?= $item->username; ?></td>
<td class="sorting_1"><?= $item->course_id; ?></td>
</tr>
<?php } ?>

Codeigniter Pagination displays links but returns NO Data

If I do not include pagination i.a. comment out $this->db->limit and remove $limit & $start from the get_category_posts() method, the values are displayed as they're meant to in a table. However, as soon as adding the limit the links are displayed but not the 'posts'. I feel there is something wrong with the pagination setup or limit business, or maybe even the position of where I have $this->db->limit (currently undernearth $this->db->from('posts'). I've been up all night trying to get this working and have have no luck on the internet, most people seem to have problems with dislaying links not actually the data itself. If somebody could point me in the direction that would be incredibly appreciated. Thank you.
MODEL:
public function get_category_posts($slug = FALSE, $limit, $start){
if($slug === FALSE){
$this->db->select('post_id, user_id_fk, post_title, post_content, post_date, slug, username');
$this->db->join('category_link_table', 'posts.post_id = category_link_table.post_id_fk');
$this->db->join('category', 'category_link_table.cat_id_fk = category.cat_id');
$this->db->join('users', 'posts.user_id_fk = users.user_id');
$this->db->from('posts');
$this->db->limit($limit, $start);
$this->db->where('category.parent_id', 0);
$query = $this->db->get();
foreach($query->result() as $row){
$data [] = $row;
}
return $data;
//return $query->result_array();
}
}
CONTROLLER:
public function catpage(){
$config['base_url'] = base_url() . "post/catpage";
$config['total_rows'] = $this->post_model->record_count();
$config['per_page'] = 2;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['posts'] = $this->post_model->get_category_posts(null, $config['per_page'], $page);
$data['links'] = $this->pagination->create_links();
$this->load->view('templates/header', $data);
$this->load->view('posts/catpage', $data);
$this->load->view('templates/footer');
}
VIEW:
<?php if(isset($posts) & ($posts <> NULL)){
foreach($posts as $post_item): ?>
<tr>
<td><p><?php echo $post_item->post_title; ?></p></td>
<td><p><?php echo $post_item->username; ?></p></td>
<td><p><?php echo $post_item->post_date; ?></p></td>
<td>Rating data</td>
<td>View data</td>
</tr>
<?php
endforeach;
}?>
Also I have a page that deals with individual slugs, so therefore I pass NULL into the methods as it of course requests 3 parameters.
Thank you.

Delete function always selects same ID - blog - Codeigniter

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

Codeigniter pagination does not work for the second page

Codeigniter pagination does not work for me. It displays page numbers and first 5 search results, but when I click on the page '2' it loads 'search_nok' view with message "Please select your options". Could you please check my code below and help me to find the mistake.
Here is my controller:
public function search($offset = 0) {
$limit = 5;
$this->load->library('form_validation');
$this->load->model('model_x');
$this->form_validation->set_rules('country', 'Country','required');
if($this->form_validation->run()) {
$country = $this->input->post('country');
$this->load->library('pagination');
$config['base_url'] = 'http://localhost/abc/cont/search/'; //where 'http://localhost/abc' is my base url
$config['total_rows'] = 14;
$config['per_page'] = 5;
$data['pagination'] = $this->pagination->initialize($config);
if ($this->model_x->did_search($country, $limit, $offset)){
$data["results"] = $this->model_x->did_search($country, $limit, $offset);
$this->load->view("search_ok",$data);
}
}
else
{
$data['message'] = 'Please select your options.';
$this->load->view("search_nok",$data);
}
}
Here is my view:
<?php
echo $this->pagination->create_links();
foreach($results as $row){
$country = $row['country'];
$city = $row['city'];
?>
<table>
<tr>
<td >
<b><?php echo $country; ?></b>
</td>
<td>
<b><?php echo $city; ?></b>
</td>
</tr>
</table>
<?php }?>
I think you are confused about Pagination. First of all, technically all of the pagination stuff:
<?php
$this->load->library('pagination');
$config['base_url'] = 'http://localhost/abc/cont/search/'; //where 'http://localhost/abc' is my base url
$config['total_rows'] = 14;
$config['per_page'] = 5;
should be in your controller, secondly, you should actually be limiting the results in your model as well, since you haven't shown your model I will come up with an example
$this->db->limit ($limit $offset //these will be defined in your controller)
$data = $this->db->get('whatever_table')->whatever_result_type.
return $data
you should define $limit in your controller and pass it over your your model function as a parameter that the function accepts
the controller should also have $offset and $limit defined
public function search($offset = 0) {
$limit = 5;
when you call your model make sure to pass these over
$this->model_x->did_search($country, $limit, $offset);
then instead of just $this->pagination->initialize($config);
do this(still in your controller remember):
$data['pagination'] = $this->pagination->initialize($config);
then echo pagination wherever you want it in your view

How can I integrate pagination to my search in CodeIgniter?

I've used codeigniter to make an easy search, no ajax or something, and I want to integrate the pagination class, I have read some examples and they use a library like this $this->table->generate($results); and I need in each result a button to edit that entry. I already did, but now with that way of showing the pagination I have a big problem, please, could anyone help me with this issue? I just need a clue or something to find in CI
I put here my model, controller and view, just in case
controller
public function searchdescription()
{
//$keyword = $this->input->post('keyword');
$keyword = $_POST['keyword'];
$this->load->model('searchdesc/searchdesc_model');
$data['retorno'] = $this->searchdesc_model->querydb($keyword);
$this->load->view('searchdesc/searchresults_view', $data);
}
model
function querydb($data,$num, $offset)
{
$queryresult = $this->db->query("select * from data where deleteflag=0 and title like '%$data%' or text like '%$data%' LIMIT $num, $offset ");
return $queryresult->result_array();
}
view
foreach ($retorno as $val)
{
echo $val['id'];
echo $val['title'];
echo $val['text'];
...here are some forms autocreated in each row that i need to keep making it
}
Here is an example (not using a model)
public function big()
{
$this->load->library('pagination');
$this->load->library('table');
$config['base_url'] = base_url().'/site/big/';
$where = "bot = '2' OR bot = '0'";
$this->db->where($where);
$config['total_rows'] = $this->db->count_all_results('visitors');
$config['per_page'] = 15;
//$config['num_links'] = 20;
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$where = "bot = '2' OR bot = '0'";
$this->db->where($where);
$this->db->select('id, ip, date, page, host, agent, spammer, country, total, refer');
$this->db->order_by("date", "DESC");
$data['records'] = $this->db->get('visitors', $config['per_page'], $this->uri->segment(3));
$this->table->set_heading('Id', 'IP', 'Date', 'Page', 'Host', 'Agent', 'Spam', 'Country', 'Total', 'Referer');
$this->db->select_sum('total', 'trips');
$query = $this->db->get('visitors');
$data['trips'] = $query->result();
$this->load->view('site_view', $data);
}
In the view where I want the table:
<?php echo $this->table->generate($records); ?>
<?php echo $this->pagination->create_links(); ?>
to add buttons in the rows do something like this
foreach($records as $row){
$row->title = ucwords($row->title);
$this->table->add_row(
$row->date,
anchor("main/blog_view/$row->id", $row->title),
$row->status,
anchor("main/delete/$row->id", $row->id, array('onClick' => "return confirm('Are you sure you want to delete?')")),
anchor("main/fill_form/$row->id", $row->id)
);
}
$table = $this->table->generate();
echo $table;
Of course you will modify to fit your needs

Categories