Codeigniter: Pass variable to the View - php

I have to table article and table comment. In the home page I want to see how many comment for earch article.
Model
function show_latest_article($start,$display,$cate)
{
$query= $this->db->get_where('news_news', array('News_Cate_ID'=>$cate),$start,$display);
if($cate==0)
{
$query= $this->db->get_where('news_news',$start,$display);
}
return $query->result();
}
function count_comment($id)
{
$query = $this->db->get_where('comment',array('comment_article_id'=>$id) );
return $query->num_rows();
}
Controller
function index() {
$this->load->model('article');
$data=array('article'=>$this->article->show_latest_article(0,8,1),
'sidebar'=>$this->article->side_bar(9),
'count_comment'=> $this->article->count_comment($id),
);
$this->load->view('page/index',$data);
}
In the view I have this
foreach($article as $art)
{
echo $art->title."<br>";
$id= $art->id;
// I want to echo number of comment here.
// Or I want to call function count_comment($id)
}

$this->load->model('article');
$data['article'] = $this->article->show_latest_article(0, 8, 1);
$data['sidebar'] => $this->article->side_bar(9);
$data['count_comment'] => $this->article->count_comment($id);
$this->load->view('page/index', $data);
And it should work.

It's not so clear, where the $id variable come from, but I suggest to join the comments table to your article. It's not a best practice to make queries within loops.
In your model:
public function show_latest_article($ids = array())
{
return $this->db
->select('articles.*, COUNT(comments.id) as comment_count')
->where_in('articles.id', $ids) // You can skip this
->join('comments', 'comments.article_id = articles.id', 'left')
->group_by('articles.id')
->get('articles')
->result();
}
In your controller:
public function index()
{
$data['articles'] = $this->article->show_latest_article(array(0, 8, 1));
$this->load->view('page/index', $data);
}
Just change the field name according to database columns. Also you can skip the where_in condition. (I'm not sure what the three number stands for).
Then in your view, you can simply access the field:
$art->comment_count
EDIT: According to your comment:
$this->db
->select('a.*, (SELECT COUNT(*) FROM comment c WHERE c.comment_article_id = a.News_News_ID ) as counta')
->get('news_news')
->result();

I am writing this answer as you provided code. It could be more simpler if you give more database details. Try below code
function index() {
$this->load->model('article');
$articles = $this->article->show_latest_article(0,8,1);
foreach($articles as $article)
{
$article->comment_count = $this->article->count_comment($article->id);
$all_article[] = $article;
}
$data=array('article'=>$all_article,
'sidebar'=>$this->article->side_bar(9)
);
$this->load->view('page/index',$data);
}
On view
foreach($article as $art)
{
echo $art->title."<br>";
$id= $art->id;
echo $art->comment_count;
}

Controller :
function index() {
$this->load->model('article');
$articles = $this->article->show_latest_article(0,8,1);
$count_comments = Array();
for($i=0;$i<count($articles);$i++){
$count_comments[$i] = $this->article->count_comment($articles->$id);
}
$count_comments =
$data=array('article'=>$articles,
'sidebar'=>$this->article->side_bar(9),
'count_comment'=> $count_comments);
$this->load->view('page/index',$data);
}
In the View :
$i=0;
foreach($article as $art)
{
echo $art->title."<br>";
$id= $art->id;
echo $count_comment[$i];
$i++;
}

Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function. Here is an example using an array:
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('blogview', $data);
Also below is the example for object
$data = new Someclass();
$this->load->view('blogview', $data);
PLEASE NOTE: Note: If you use an object, the class variables will be turned into array elements.
You can find out more from below ref URL
Ref: https://ellislab.com/codeigniter/user-guide/general/views.html

First of all in your controller you get count_comment only for specific article ID and not for all articles so you cant do foreach to display comment count of each article.
You need to setup you model better and in model function show_latest_article to use JOIN comments table and do count comment in query.
I will help you with query if you provide me more info about database table of article and comments.
SELECT
article.*,
COUNT(comment.id),0) AS numberOfCommments
FROM article
LEFT JOIN comment
ON comment.article_id = article.id
GROUP BY article.id

Related

How to join these tables in codeigniter

I am facing problem to join these tables and also know how to make controller code to view data in view file with text boxes.
public function get_order_return_info()
{
$this->db->select('tbl_order_details.*', false);
$this->db->select('tbl_order_details.order_details_id', false);
$this->db->select('tbl_order.order_id', false);
$this->db->select('tbl_product.product_id', false);
$this->db->select('tbl_inventory.product_quantity', false);
$this->db->from('tbl_order_details');
$this->db->join('tbl_order', 'tbl_order_details.order_id = tbl_order.order_id ', 'left');
$this->db->join('tbl_product', 'tbl_order_details.product_code = tbl_product.product_id ', 'left');
$this->db->join('tbl_inventory', 'tbl_product.product_id = tbl_inventory.product_id ', 'left');
$query_result = $this->db->get();
$result = $query_result->result();
return $result;
}
You can use MVC to solve this
//Controller
function get_data() {
$data['list'] = $this->your_model->get_data();
$this->load->view('your_view/location',$data);
}
//Model
function get_data() {
$sql = "your_query";
$list = $this->db->query($sql)->result_array();
return $list;
}
//View
foreach($list as $data) {
echo $data['your_selected_field']; // it could be table,text field,or just text
}
API Reference : https://www.codeigniter.com/user_guide/database/results.html#result-arrays
Hope this helps
First u can create OrderModel to work with order table. Then create function get_order_data.
//Order Model
public function get_orders() {
// your db query to get orders
return $result;
}
Then u can load model in controller using $this->load->model('OrderModel'); Best place is __construct to load model
And call your get_orders() function
// Your controller
// Create data array to store front data
$data = [];
$data['orders'] = $this->OrderModel->get_orders();
After getting $orders pass it to view using following codes
$this->load->view('path/to/view', $data);
Finally u can call your order data in view using $orders
I hope this will help u
You need to set alias to the table to function it properly like this.
$this->db->select('a.*,a.order_details_id, b.order_id ', false);
$this->db->from('tbl_order_details as a');
$this->db->join('tbl_order as b', 'a.order_id = b.order_id ', 'left');
If you want select 1 row only you need to use this function.
$this->db->get('tbl_order_details')->row_array();
or if you want all result row you need to use this.
$this->db->get('tbl_order_details')->result_array();
On your controller you should add this lines to pass your result on your view page.
public function index()
{
$data['orderDetails'] = $this->your_model->get_order_return_info();
$this->load->view('pages/yourview/index',$data);
}
And finally to set your order details to the text boxes. You need to echo it inside the text boxes like this.
<input type="Text" name="orderID" value="<?php echo $orderDetails['order_id'];?>" >
If you use result_array() you need to use foreach loop to echo it.

How make count comment with codeigniter,

I'm working on a project. how to calculate comment by id?
example
controler:
public function comments() {
$id_alat = $this->db->where('id_alat');
$com = $this->mcrud->getComent($id_alat);
$com = $this->mcrud->getComent($id_alat);
$data = array (
'com' => $com,
'content' => 'instrument/instrument');
$this->load->view('layouts/wrapper', $data);
}
models:
public function getComent($id_alat) {
$sql = "SELECT count (*) as num FROM WHERE tbcoment $id_alat tbcoment.id_alat = {}";
$this->db->query($sql);
}
view:
comments: <?php echo $com; ?>
Use following code for model
Your Model
public function getComent($id_alat)
{
$sql = "SELECT count (*) as num FROM WHERE tbcoment.id_alat = '$id_alat'";
$res=$this->db->query($sql)->row_object();
return $res->num;
}
Note: Don't use spaces inside php tags and variables.
Ex01: $ id_alat should come $id_alat
Ex02: $ this-> mcrud-> getComent ($ id_alat); should come $this->mcrud-> getComent($id_alat);
Code Example
In controller
function comments () {
$id_alat = '';//Asign data to here
$data['com'] = $this->Model_name->getComent($id_alat);
$data['content'] = 'instrument / instrument';
$this->load->view ('layouts/wrapper', $data);
}
In Model
function getComent($id_alat) {
$query =$this->db->query("SELECT * FROM table_name WHERE tbcoment='$id_alat'");//cahnge table name, and argument that you want
$result = $query->result_array();
$count = count($result);
return $count;
}
In view
comments: <?php echo $com; ?>
you can also use this code:
$this->db->where('id',$id)
->from('table_name')
->count_all_results();
this can be used either on MVC(Model, View, Controller);
you can find this code on the user guide

Codeigniter php MVC

I have a table called 'News' with three columns: 'id', 'title' and 'details'
I have a function ('get_entry') inside a codeigniter model class (called 'News_model')
function get_entry()
{
$this->load->database();
return $this->db->select('id,title,details')->from ('news');
$data['newsarray'] = $this->db->row_array();
return $data['newsarray'];
}
I am connecting to the db so that is not the problem.I want to return an iterable array from get_entry() by calling the function from a controller file with the followlwing code. I want to push it into another array (called '$data['theNews']') using the code below.
foreach ($this->News_model->get_entry() as $key => $value){
array_push($data['theNews'],$value->title);
}
I have been using the code on this (https://www.codeigniter.com/user_guide/general/models.html) as a template (in particular the function 'get_last_ten_entries()' but I think I am close with the code I posted above. I would appreciate any help.
About your code:
You have two 'return' in your get_entry function:
function get_entry()
{
$this->load->database();
// First
return $this->db->select('id,title,details')->from ('news');
$data['newsarray'] = $this->db->row_array();
// Second
return $data['newsarray'];
}
Change it to:
function get_entry()
{
$this->load->database();
$query = $this->db->select('id,title,details')->from('news');
$data['newsarray'] = $query->row_array();
return $data['newsarray'];
}
It should work now.
Some advices:
Don't use Codeigniter 2 anymore. Version 3 is alive.
If you plan to return whole table columns, i suggest you to use the following code for the query:
$query = $this->db->get('news', 1, 20);
Where 1, 20 is the limit.
Now you can get the result:
return $query->result();
A simple example:
function get_entry()
{
$this->load->database();
$query = $this->db->get('news', 1, 20);
return $query->result();
}
This method returns the query result as an array of objects that you can print like so in your controller:
$news_array = $this->News_model->get_entry();
foreach ($news_array as $news)
{
echo $news->id;
}
Look at CI 3 Query Builder query builder for more examples.
One more suggestion, just autoload the database library in application/config/autoload.php if you need it globally.
Changing the code to this in the function worked:
function get_entry()
{
$this->load->database();
$query = $this->db->get('news');
//return $query->result();
foreach ($query->result() as $row)
{
echo "</br>";
echo $row->id;
echo "</br>";
echo $row->title;
echo "</br>";
echo $row->details;
echo "</br>";
}
}
Calling the function like so prints it out:
$news_array = $this->News_model->get_entry();

how to implement nested comments 2 levels deep in codeigniter

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?

How to display total comments

Whatsup codeigniters!
I want to display total comments of my blog that I am building with codeigniter.
In my controller I have:
function index() {
$data['query'] = $this->blog_model->get_all_entries();
$this->load->view('blog/index',$data);
}
Function index() gets all posts.
and I have
public function post($id) {
$data['query'] = $this->blog_model->get_post($id);
$data['comments'] = $this->blog_model->get_post_comment($id);
$data['post_id'] = $id;
$data['total_comments'] = $this->blog_model->total_comments($id);
$this->load->view('blog/index',$data,TRUE);
$this->load->helper('form');
$this->load->library(array('form_validation','session'));
//validation rules for post function
$this->form_validation->set_rules('commentor','Name','required');
$this->form_validation->set_rules('email','Your email','required|valid_email');
$this->form_validation->set_rules('comment','Comment','required');
if($this->blog_model->get_post($id))
{
foreach($this->blog_model->get_post($id) as $row)
{
//set page title
$data['title'] = $row->entry_name;
}
if($this->form_validation->run() == FALSE)
{
//if validation runs FALSE
$this->load->view('blog/post',$data);
}
else
{
//if valid
$name = $this->input->post('commentor');
$email = strtolower($this->input->post('email'));
$comment = $this->input->post('comment');
$post_id = $id;
$this->blog_model->add_new_comment($post_id,$name,$email,$comment);
$this->session->set_flashdata('message', '1 new comment added!');
redirect('blog/post/'.$id);
}
}
else
show_404();
}
Basically, post($id) gets a post with id (single post) and display comments. I can print total comments number in single post. But how do i print total comments number in index() function where all posts are listed. Thank you!
Use this active record
$this->db->select("post_id , count(comment) as total_comments");
$this->db->group_by('post_id');
$query = $this->db->get('comments');
This generate this sql query
SELECT
post_id,
count(comment) as total_comments
FROM comments
GROUP BY post_id
Means this selects posts , count of posts for each comment and seperate them by post. For understanding Here is the table Structure
Comments
id count(comment) post_id
Now the query will first fetch all the comments then it will use group by to seperate posts giving you total comments for each post.
Try to do something like this
in Model
public function fetch_all_comment()
{
$query = $this->db->get('comments');
return $query->result();
}
In Controller
$data['all_comments'] = $this->model_name->fetch_all_comment();
$this->load->view('viewname',$data);
In View
For this you have to call model in your view. for example if you want to display post name.
Load Model in view
foreach ($all_comments as $row)
{
echo $row->post;
echo $total_no_post = $this->model_name->fetch_total_no_of_comment_in_post($row->postid);
}
Count no of comment in this function fetch_total_no_of_comment_in_post

Categories