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 } ?>
Related
function mostViewedTracks() {
$this->load->database();
$this->db->select("*");
$this->db->from("file");
$this->db->order_by("views", "desc");
$this->db->limit(8);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$results = $query->result();
}
return array();
}
when i run this model it gives error that invalid argument supplied for foreach()
this is my view code:
<?php if( !empty($most_viewed) ) { ?>
<?php foreach($most_viewed as $row): ?>
<a href="<?php echo base_url('index.php/home/track');?>/<?php echo $row->id;?>" class="list-group-item">
<img class="track-list-img" src="<?php echo base_url('assets/img/music');?>/<?php echo $row->id;?>.jpg">
<div class="list-track-infoo">
<h4 class="list-group-item-heading"><?php echo $row->title;?><span class="badge"><?php echo $row->views;?><span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span></span> </h4>
<p class="list-group-item-text"><?php echo $row->singer;?></p>
</div>
</a>
<?php endforeach; ?>
<?php} ?>
Updated
Controller
function track() {
$id = $this->uri->segment(3);
$data1['track'] = $this->view_models->track($id);
$data1['most_viewed'] = $this->view_models->mostViewedTracks();
$this->load->view('includes/header');
$this->load->view('track', $data1);
$this->load->view('includes/footer');
}
I have tried my best to solve this problem but all in vain
You need to change two mistakes,
You should return the `$result` array in your model like,
$results = $query->result();
return $results;
And in foreach change $row1 to $row which produces the error. see,
<?php foreach($most_viewed as $row): ?>
Instead of return array(); you have to return result set from models file
if($query->num_rows() > 0)
{
return $query->result();// return result set
}else{
return FALSE;//
}
IN controller you have to call your models function as
$data1['most_viewed'] = $this->view_models->getFeaturedTracks();// change mostViewedTracks to getFeaturedTracks
In view use it as
<?php foreach($most_viewed as $row): ?>// remove $row1 to $row
Function should like this....
function getFeaturedTracks() {
$results = array();
$this->load->database();
$this->db->select("*");
$this->db->from("file");
$this->db->order_by("views", "desc");
$this->db->limit(8);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$results = $query->result();
}
return $results;
}
I'm learning CI and latest I've been tasked to do is pagination. So I followed this tutorial as it seemed relatively nicely made and explained. Link
The pagination works and its great. Now I wanted to make a read more under each post, making each post open separately with its full description. That also works, but when I click a link to go back to the pagination index, the list starts from the beginning, no matter which post I clicked. I'm not sure how to add the page I want the return link to take me back so I'll just post this here and hopefully it won't be too hard for someone to tell me.
If someone is confused what I'm after, just look at the last view readmore_paginate. In it, the last link should contain a number back
to the page, but idk how to put or what to put there.
Controller
public function paginate()
{
$config = array();
$config['base_url'] = base_url()."welcome/paginate";
$config['total_rows'] = $this->blog_model->countPosts();
$config['per_page'] = 2;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0; //TERNARY OPERATOR (? = TRUE) (: = FALSE)
$data['results'] = $this->blog_model->fetchPosts($config['per_page'], $page);
$data['links'] = $this->pagination->create_links();
$this->load->view('header');
$this->load->view("p_content", $data);
$this->load->view('footer');
}
public function readMore_Paginate()
{
$id = $this->input->get('postid');
$data['post'] = $this->blog_model->getSpecificPost($id);
$this->load->view('header');
$this->load->view('readmore_paginate', $data);
$this->load->view('footer');
}
Model
public function countPosts()
{
return $this->db->count_all("Blogposts");
}
public function fetchPosts($limit, $start)
{
$this->db->select('*');
$this->db->from('Blogposts');
$this->db->join('Blogcategories', 'Blogposts.postcatid=Blogcategories.id');
$this->db->limit($limit, $start);
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
View p_content
<div class="col-md-8">
<table class="table">
<tbody>
<?php
foreach ($results as $key) {
echo "<tr><th><h2><kbd><font color='yellow'>".$key->postname."</font></kbd></h2><kbd><font color='lime'>".date("d M Y",strtotime($key->postdate))."</font></kbd> <kbd><font color='cyan'>".$key->catname."</font></kbd></th></tr>";
echo "<tr><td><blockquote>".mb_substr($key->postdesc, 0,80,'UTF-8')."...";?>
read more</blockquote>
<?php } ?>
</tbody>
</table>
<p><?php echo $links; ?></p>
</div>
View readmore_paginate
<div class="col-md-8">
<table class="table">
<tbody>
<?php
foreach ($post as $key) {
echo "<tr><th><h2><kbd><font color='yellow'>".$key['postname'].
"</font></kbd></h2><kbd><font color='lime'>".
date("d M Y",strtotime($key['postdate']))."
</font></kbd> <kbd><font color='cyan'>".
$key['catname']."</font></kbd></th></tr>";
echo "<tr><td><blockquote>".$key['postdesc']."</blockquote>"; ?>
Back to Posts
<?php }
?>
</tbody>
</table>
</div>
Controller
$page = $this->input->get('page') ?
$this->input->get('page') :
$this->uri->segment(3) ?
$this->uri->segment(3) :
0;
$data['results'] = $this->blog_model->fetchPosts($config['per_page'], $page);
$data['links'] = $this->pagination->create_links();
$data['page'] = $page; // add this
view p_content
read more</blockquote>
view readmore_paginate
Back to Posts
Friends I'm Unable to get open positions Sum. here is my code. I am getting 1(one) instead of total sum. Help me to solve this issue.
Controller:
function index(){
$userId = $this->phpsession->get("userId");
$userType = $this->phpsession->get('userType');
$date = date("Y-m-d");
if(!$userId && !$this->phpsession->get("userType")){
redirect(base_url().'user');
}
$config['base_url'] = base_url().'requirement/index';
$config['total_rows'] = $this->requirement_model->GetRequirement(array("count"=>true));
$config['per_page'] = 5;
$config['cur_tag_open'] = '<a>';
$config['cur_tag_close'] = '</a>';
$this->pagination->initialize($config);
$options['offset'] = $this->uri->segment(3);
$options['limit'] = $config['per_page'];
$options['join']=true;
$data['clients'] = $this->client_model->ajaxclient();
$data['requirements'] = array(""=>"Choose requirement");
$data['requirement'] = $this->requirement_model->GetRequirement($options);
$data['links'] = $this->pagination->create_links();
$data['totalactive']=$this->requirement_model->GetRequirement(array("find"=>true));
$data['totalrequirement']=$this->requirement_model->GetRequirement(array("totalreq"=>true));
$data['openpositions']=$this->requirement_model->GetRequirement(array("openpos"=>true));
//print_R($data['openpositions']);exit;
//echo "<pre>"; print_R($this->db->last_query()); exit;
$data['page_title'] = "Requirement Details";
$this->layout->view("requirement/index",$data);
}
This is my model function
Model:
function GetRequirement($options = array()){
if(isset($options['requirementId']))
$this->db->where('requirementId',$options['requirementId']);
if(isset($options['clientName']))
$this->db->where('clientName',$options['clientName']);
if(isset($options['limit']) && isset($options['offset']))
$this->db->limit($options['limit'], $options['offset']);
else if(isset($options['limit']))
$this->db->limit($options['limit']);
$this->db->order_by("activateddate", "DESC");
if(isset($options['join'])){
$this->db->select('r.*,c.clientName as cName');
$this->db->from('requirement as r');
$this->db->join('clients as c','c.clientId=r.clientName');
$query=$this->db->get();
if(#$options['requirementId']) return $query->row(0);
return $query->result();
}
if(isset($options['find'])){
$this->db->select('distinct(clientName)');
$this->db->from('requirement');
$this->db->where('(clientName) and (noofpositions > 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
if(isset($options['totalreq'])){
$this->db->select('requirementName');
$this->db->from('requirement');
$this->db->where('(noofpositions > 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
if(isset($options['openpos'])){
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
$query = $this->db->get('requirement');
if(isset($options['count'])) return $query->num_rows();
if(#$options['requirementId']) return $query->row(0);
return $query->result();
}
This is my View page
View:
<div class="inner">
<h3><?php echo $openpositions; ?></h3>
<p>Total Positions Opened</p>
</div>
You are using sum which is an aggregate function and with out group by it will take whole table as one group in if(isset($options['openpos'])){ ... } part of code of your model your are returning num_rows() which returns the no. of rows so in your case there will be one row with the value of sum therefore you are getting result as 1 change your
if (isset($options['openpos'])) {
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$query = $this->db->get();
return $query->row()->openpos;
}
I think the mysql statement has an error.
Change the following line:
$this->db->where('(closedPos = 0) ');
To
$this->db->where('closedPos', 0);
remove the following line: (this will count all rows and return the value, which you do not want)
$this->db->countall();
If this does not solve your problem you could try outputting the mysql statement by adding exit($this->db->last_query()); to try and find the problem, like this:
if(isset($options['openpos'])){
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$this->db->count_all();
$query=$this->db->get();
// output last query
exit($this->db->last_query());
return $query->num_rows();
}
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.
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