I am trying to make a bootstrap slider with CodeIgniter, the slider images should be pulled from the database.
each post has a unique slider, so I have 2 database tables, one for the posts and the other for the slides.
the issue is I can't loop through the slides table to pull out the slides that assigned to the post.
I did a join tables between the posts and the slides table so I can get the associated slides, but the result is only loading one slide.
Model:
public function get_yachts($slug = FALSE){
if ($slug === FALSE) {
$query = $this->db->get('yachts');
return $query->result_array();
}
$this->db->join('yacht_slider', 'yacht_slider.yacht_slide_id = yachts.id');
$query = $this->db->get_where('yachts', array('slug' => $slug));
return $query->row_array();
}
Controller:
public function view($slug = NULL){
$data['yacht'] = $this->yacht_model->get_yachts($slug);
$data['title'] = 'Yachts';
$this->load->view('templates/header', $data);
$this->load->view('yachts/view', $data);
$this->load->view('templates/footer');
}
}
In my HTML code, when I try to load the slides like this <?php echo $yacht['slide'];?> I only get one row from slides table, so how can I loop to get the rest of the slides. I tried foreach loop and other methods, but none worked.
Hope this will help you :
Your model get_yachts should be like this :
public function get_yachts($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get('yachts');
return $query->result_array();
}
else
{
/*$this->db->select('yachts.title as ytitle');*/
$this->db->join('yacht_slider', 'yacht_slider.yacht_slide_id = yachts.id');
$query = $this->db->get_where('yachts', array('slug' => $slug));
return $query->result_array();
}
}
Controller will remain the same.
In view access $yacht like this:
this will work when slug is either empty or not empty
<?php
if (! empty($yacht))
{
foreach ($yacht as $key => $item) {
echo $item['slide'];
}
}
?>
Related
I am working on an online newspaper/blogging application with CodeIgniter 3.1.8 and Bootstrap 4.
At the bottom of the single post view, I want to add a link to the next post (as well as one to the previous post). For this, I need to get the data (slug, title, etc), of the next post (row in the posts table).
For this purpose, I have added this method to my Posts_model model:
/* Next post */
public function get_next_post($slug) {
$query = $this->db->get_where('posts', array('slug' => $slug));
if ($query->num_rows() > 0) {
$data = $query->next_row();
return $data;
}
}
In the controller I have:
public function post($slug) {
//more code
$data['post'] = $this->Posts_model->get_post($slug);
$data['next_post'] = $this->Posts_model->get_next_post($slug);
print_r($data['next_post']);
//more code
}
EDIT: In the Posts_model, I now have:
/* Next post */
public function get_next_post($slug) {
$query = $this->db->get('posts');
$row_index = 6;
$data = $query->row_array($row_index);
if ($query->num_rows() > 0) {
$data = $query->next_row();
return $data;
}
}
/* Prev post */
public function get_prev_post($slug) {
$query = $this->db->get('posts');
$row_index = 6;
$data = $query->row_array($row_index);
if ($query->num_rows() > 0) {
$data = $query->previous_row();
return $data;
}
}
That means that if I could get the current post's index by slug, I could replace this hardcoded index of the 7th post - $row_index = 6 - and the problem would be solved.
How do I do that?
// Your_model.php
...
public function getPost($slug) {
$this->db->where('slug', $slug);
return $this->db->get('posts_table')->row_array();
}
public function getPrevPost($currentPostId) {
$this->db->where('id <', $currentPostId);
$this->db->order_by('id', 'desc');
$this->db->limit(1);
return $this->db->get('posts_table')->row_array();
}
public function getNextPost($currentPostId) {
$this->db->where('id >', $currentPostId);
$this->db->limit(1);
return $this->db->get('posts_table')->row_array();
}
// Yourcontroller.php
...
public function getPost($slug) {
$post = $this->your_model->getPost($slug);
$data = [
'thePost' => $post,
...
'prevPost' => $this->your_model->getPrevPost($post['id']),
'nextPost' => $this->your_model->getNextPost($post['id']),
...
];
...
}
EDIT: this post answers the original question. In the meantime below code was used in an edit by OP.
you need to return a result of your query: $data = $query->row_array();
And get_where() is limiting the record-set to one record, hence there is no next record. You need to return the complete record-set with $this->db->get('posts'). In case you know the row_number (e.g.: 5) of the row containing $slug, you can point to it. The next_row shown, is row number 6.
public function get_next_post($slug) {
$query = $this->db->get('posts'); // querying the whole data-set
$data = $query->row_array(5); // the missing line
if ($query->num_rows() > 0) {
$data = $query->next_row();
return $data;
}
}
now you should get your next row (if exists), see Result Rows
I am new to codeigniter and could be better at php. I have a news item being retrieved from the database table news, it has a foreign key of partner_id that is tied to the partners table. I want to get that value and use it to get the associated partner and display it's info. This is the latest of my attempts. I think I might be making it too hard. All relevant files are below. Thanks in advance.
In the model if the $id_partner is being assigned in the get_news function I don't think it is passing to the get_partner function.
news_model.php
public function get_news($slug_news = FALSE)
{
$this->load->helper('array');
if ($slug_news === FALSE)
{
$news_query = $this->db->get('news');
return $news_query->result_array();
}
$news_query = $this->db->get_where('news', array('slug' => $slug_news));
return $news_query->row_array();
global $id_partner;
$id_partner = element('partner_id', $news_query);
}
public function get_partner($id_partner = FALSE){
$partners_query = $this->db->get('partners');
$partners_query = $this->db->get_where('partners', array('id' => $id_partner));
return $partners_query->row_array();
}
The $slug_news in the view function doesn't apply to the partner part (obviously). but can I have another function?
controller, news.php
public function view($slug_news)
{
$data['news_item'] = $this->news_model->get_news($slug_news);
$partner_data['partner_listing'] = $this->news_model->get_partner($id_partner);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('news/news_partner', $partner_data);
$this->load->view('templates/sidebar');
$this->load->view('templates/footer');
}
view1, news/view.php
<?php
echo '<img src="/images/'.$news_item['thumb'].'" />';
echo '<h2>'.$news_item['title'].'</h2>';
echo $news_item['text'];
echo $news_item['bus_name'];
?><br>
and view2, news/news_partner.php
<?php
echo '<h2>'.$partner_listing['bus_name'].'</h2>';
echo $partner_listing['address1'];
echo $partner_listing['address2'];
echo $partner_listing['city'];
echo $partner_listing['state'];
echo $partner_listing['phone'];
echo $partner_listing['email'];
?>
Your model is a little all over the place. To start, the two lines after the return are never called in get_news. I would just simplify the model and do a simple join:
public function get_news()
{
$this->db->select('*');
$this->db->from('news');
$q = $this->db->join('partners', 'news.partner_id = partners.id');
return $q->result();
}
Here is what I put with your code:
public function get_news($slug_news = FALSE)
{
if ($slug_news === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
$this->db->select('*');
$this->db->from('news');
$query_news = $this->db->join('partners', 'news.partner_id = partners.id');
return $query_news ->result();
}
I only used the "view.php" view as well. Does $slug_news need to be in there somewhere? How does it know what line to get? Thanks for your help, I am having so much trouble.
I am trying to implement a commenting system on my website that is only two levels deep for example you will have the main comment and replies to that comment but it does not go any further:
main comment 1
(sub_comment1)
(sub_comment2)
main comment 2
(sub_comment1)
(sub_comment2)
(sub_comment2)
etc...
Make sense?
I am creating the site in codeigniter but i think a basic php solution will do.
each row in my database table has an id and a parent_id, if the parent id is 0 then its a main comment and if its a sub-comment it will have the id of its parent comment in parent_id.
how to I feed a two dimensional array with the parent and child comments in the right order.
My current code is like so: The controller:
function status_comments($id){
$this->load->model('status_model');//load the status model
$this->load->model('comment_model');//load the comment model
$status = $this->status_model->get_entry_and_category($id);
$comments = $this->comment_model->get_comments($id);
if($status !== false) {
if($comments !== false) {
foreach($comments as $comment){
if($comment->reply_id == 0){
$comment =
}
}
$content_data['comments'] = $comments;
}
$content_data['status'] = $status;
$data['content'] = $this->load->view('status_view', $content_data, TRUE);
$data['title'] = $status->title.' - High Value Status';
$data['page_title'] = $status->title;//The page H1 tag
$this->load->view('home', $data);
}
else
{
$this->session->set_flashdata('invalid', '<p class="rejectionalert"><span>The status you tried to view does not exist.</span></p>');
redirect('home');
}
}
The model function:
//Gets comments associated with an individual status
function get_comments($status_id, $offset=null, $limit=null)
{
$this->db->select('id, comment, nickname, created, reply_id');
$this->db->from('comments');
$this->db->where('active', 1);
$this->db->where('status_id', $status_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
}
return false;
}
This works but its using more than one query, the model:
function get_comments($status_id, $limit=NULL, $offset=NULL)
{
$this->db->where(array('status_id' => $status_id, 'reply_id' => 0));
$query = $this->db->get('comments', $limit, $offset);
$parents = $query->result_array();
$comments = array();
foreach($parents as $key => $comment)
{
array_push($comments, $comment);
$this->db->order_by('created', 'ASC');
$this->db->where(array('status_id' => $status_id, 'reply_id' => $comment['id']));
$comments = array_merge($comments, $this->db->get('comments')->result_array());
}
return $comments;
}
I thought it would be more efficent to make one query of all comments, index them into an array by their id, and iterate over them again to find their children. I still dont know how to implement that?
Hey guys !
Well I was trying out codeigniter but it seems to me that I have made some kind of mess while trying to retrieve and display the data from the tables
here is the code snippet.
I want to retrieve all the articles stored in my article table along with that I need to pull out all the tags associated with each article from the relationship table and the tag table called articleTagRelation and tags respectively
Table structure :
Article table : articleID, articleContent, date
Tags table : tagID, tagName
articleTagRelation : aricleID,tagID {Combination of both is my primary key}
CI model :
article_model.php
public function getAllTags($postId){
$this->db->select('articleTagRelation.tagId as tagId, articleTagRelation.postId as postId, article.tagName as tagName,');
$this->db->from('articleTagRelation');
$this->db->join('Tags','Tags.tagId = articleTagRelation.tagId');
$this->db->where('ArticleTagRelation.articleId',$postId);
$qTag = $this->db->get();
if($qTag->num_rows() > 0){
foreach ($qTag->result() as $tag) {
return $tag;
}
}
}
public function getAllArticles(){
$this->db->select('*');
$this->db->from('Article');
$this->db->order_by('date','desc');
$query=$this->db->get();
if($query->num_rows()>0){
foreach ($query->result() as $row) {
$data['row'] = $row;
$data['articletags'] = $this->getAllTags($row->articleId); // I'm trying to get get a array of all the associate tags.
$post=array($data['row'],$data['articletags']);
}
}else{
echo 'nothing found !';
}
return $post;
}
my controller file
article.php
I'm calling this function in the index function
$data['rows'] = $this->blog_model->getAllArticles();
and then loading the view by passing the data array
now the part where things get messy
in my view
echo $r->articleId // works fine
echo $r->articletags->tagId //gives me a error message
Can any one help me out in printing those tagIds
First you don't need the foreach at all to get the tag information, it comes back from a query_result.
like this...
if($qTag->num_rows() > 0){
return $qTag->result();
}
else {
return array(); //return empty array if no tags
}
Then to build your article, do this with getAllArticles()
public function getAllArticles(){
// removed uneccessary select and from
// the below accomplishes the same thing
$this->db->order_by('date','desc');
$query = $this->db->get('Article');
if ( $query->num_rows() > 0 ) {
// store the result in a variable you will end up returning
$articles = $query->result();
// make sure you foreach by reference so that changes you make
// to the interated $article will be made to the actual article
// result
foreach ($articles as &$article) {
// create a new property of your article "tags" and save an
// array of tags in it
$article->tags = $this->getAllTags( $article->articleId );
}
} else {
echo 'nothing found !';
}
return $articles;
}
The last thing to note is that when you now reference $r->tags that is an array, so you can foreach it to process all tags, OR reference an index like $r->tags[3]->tagId
if($qTag->num_rows() > 0){
foreach ($qTag->result() as $tag) {
$tags[] = $tag; //this create the array with the result
}
return $tags;
}
"$r->articletags->tagId" only works if you return results as an object, use "$r->articletags['tagId']" instead.
I have reworded my question to help gain my specific answer, sorry if my last question was confusing:
I have an issue with trying to delete a row from the database but also incorporate how to unlink the to images from different locations. I cannot get the row to delete or the images to unlink.
Here is my -> db structure
My image locations are:
fullpath = /includes/uploads/gallery/
thumbpath = /includes/uploads/gallery/thumbs/
Ideal Situation:
What my ideal situation would be is when the delete link is clicked that it will run the function within the index function and then reload the same page with a success message -> I have not successfully been able to get them to work.
My code:
Model:
function deleteImage($id,$path){
$this->db->delete('images', array('id' => $id));
if($this->db->affected_rows() >= 1) {
if(unlink($path)
return TRUE;
} else{
return FALSE;
}
}
View:
<?php if(is_array($get_images)): ?>
<?php foreach($get_images as $image): ?>
<img src ="<?=base_url()?>includes/uploads/gallery/thumbs/<?=$image->thumbpath?>" alt="<?= $image->description?>"> Delete
<?php endforeach; ?>
<?php endif; ?>
Controller:
function index() {
if(!$this->session->userdata('logged_in')) {
redirect('admin/home');
}
// Main Page Data
$page['get_images'] = $this->image_model->getImages();
$data['cms_pages'] = $this->navigation_model->getCMSPages();
$data['title'] = 'Delete Gallery Image';
$data['content'] = $this->load->view('admin/deleteimage',$page,TRUE);
$this->load->view('admintemplate', $data);
}
function delete_data($record_id)
{
$query = $this->db->get_where('projukti_committee',array('record_id' => $record_id));
if( $query->num_rows() > 0 )
{
$row = $query->row();
$picture = $row->picture;
unlink(realpath('assets/photo/'.$picture));
$this->db->delete('projukti_committee', array('record_id' => $record_id));
return true;
}
return false;
}
What you're looking for if you're using active record is:
$this->db->delete();
Now from memory this will only return false if an error has occurred, so will constantly return true. But it's ok we can use another function to check whether the row was deleted.
Oh and you will also want to pass into the function the path of the file you want deleting.
function deleteImage($id,$path) {
$this->db->delete('table', array('id' => $id));
if($this->db->affected_rows() >= 1){
if(unlink($path))
return TRUE;
} else {
return FALSE;
}
}
Presumably you have an image ID of some sort.
Append the ID to the deleteimage/delete URI.
Create a method that deletes the ID from your table, and use PHP's unlink($path) function to actually delete the image.