im joining 3 tables: users, posts and comments in the following code :
public function join_user_post(){
$this->db->select('
posts.post_body,
posts.date_created,
users.username,
users.user_image,
comments.comment_body,
comments.date_created
');
$this->db->from('posts');
$this->db->join('users', 'users.id = posts.post_user_id ');
$this->db->join('comments', 'comments.comment_post_id = posts.post_id ');
$query = $this->db->get();
return $query->result();
}
then passing this array data to the homepage view via controller:
<?php
class Home extends CI_Controller{
public function index(){
$this->load->model('user_model');
$data['posts'] = $this->user_model->join_user_post();
$this->load->view("user/homepage",$data);
}
}
?>
in the homepage view im trying to echo the post with the username and user image, then looping through comments of each post and echo it out
<body>
<?php include 'navbar.php';?>
<?php foreach($posts as $post): ?>
<div>
<img src="<?php echo $post->user_image ?><br>">
<?php echo $post->username ?><br>
<?php echo $post->post_body ?><br>
<?php echo $post->date_created ?><br>
<?php foreach($posts as $post): ?>
<?php echo $post->comment_body ?><br>
<?php echo $post->date_created ?><br>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</body>
but im rather getting all comments on every post instead of getting the comments that are related to specific post id, the foreach is looping through all comments and echo them on every post, if i remove the foreach loop it will echo only one comment at each post
what should i do to solve this issue?
The problem is when you join posts with comments it return many records of comments with the same post. You can modify a little bit first in your controller to store each post with comments belong to it:
function index()
{
$this->load->model('user_model');
$comments = $this->user_model->join_user_post();
$posts = array();
foreach ($comments as $comment) {
if (array_key_exists($comment->post_id, $posts)) {
$posts[$comment->post_id]['comments'][] = $comment;
} else {
$posts[$comment->post_id]['post_body'] = $comment->post_body;
$posts[$comment->post_id]['username'] = $comment->username;
$posts[$comment->post_id]['date_created'] = $comment->date_created;
$posts[$comment->post_id]['user_image'] = $comment->user_image;
$posts[$comment->post_id]['comments'][] = $comment;
}
}
$data['posts'] = $posts;
$this->load->view("user/homepage", $data);
}
And in your view:
<div>
<img src="<?php echo $post['user_image'] ?><br>">
<?php echo $post['username'] ?><br>
<?php echo $post['post_body'] ?><br>
<?php echo $post['date_created'] ?><br>
<?php foreach ($posts['comments'] as $comment) : ?>
<?php echo $comment->comment_body ?><br>
<?php echo $comment->date_created ?><br>
<?php endforeach; ?>
</div>
Related
how i can sort some informations without $id? My problem is, that i ca read all teams and users. but how i can sort this?
So that i get a team and the players from this team in one box. WIth my code i have all users in all boxes.
Can i foreach in a foreach?
view what i try:
<?php foreach ($teams as $item): ?>
<div class="col-xs-12">
<?php echo $item->teamname ?>
</div>
<?php foreach ($users as $item): ?>
<div class="col-xs-12">
<?php echo $item->username ?>
</div>
<?php endforeach ?>
<?php endforeach ?>
This is my database
table users
user_id username team_id
1 paul 1
2 tom 2
3 brad 1
4 pim 2
table team
team_id teamname
1 team1
2 team1
Now i have a subside like domaincom/teams
And i want on this side
team 1 : paul, brad
team 2 : tom, pim
controller:
<?php
class Teams extends CI_Controller {
public $layout = 'full';
public $module = 'teams';
public $model = 'Teams_model';
public function __construct() {
parent::__construct();
$this->load->model($this->model);
$this->_primary_key = $this->{$this->model}->_primary_keys[0];
}
public function index()
{
$data['teams'] = $this->{$this->model}->get_teams();
$data['users'] = $this->{$this->model}->get_users();
$data['teamsWithUsers'] = $this->{$this->model}->get_users_by_team();
$data['items'] = $this->{$this->model}->get();
$this->load->view($this->module, $data);
}
}
this is my model
<?php
class Teams_model extends CI_model
{
public $_table = 'teams';
public $_primary_keys = array('teams_id');
function get_teams()
{
return $this->db->get('teams')->result();
}
function get_users()
{
return $this->db->get('users')->result();
}
function get_users_by_team($teamID = null)
{
$this->db->select('u.user_id, u.username, u.team_id, t.teamname');
$this->db->from('users AS u');
$this->db->join('teams AS t', 't.team_id = u.team_id');
if ($teamID != '') {
$this->db->where('t.team_id', $teamID);
}
$this->db->order_by('t.teamname', 'ASC');
$this->db->order_by('u.username', 'ASC');
$query = $this->db->get();
return $query->result();
}
}
What i looking for is this view sample
what about that?
your controller
public function index()
{
$data['teams'] = $this->{$this->model}->get_teams();
$data['users'] = $this->{$this->model}->get_users();
$arrUsersPerTeam = [];
foreach($data['users'] AS $objUser)
{
$arrUsersPerTeam[$objUser->team_id][] = $objUser;
}
$data['arrUsersPerTeam'] = $arrUsersPerTeam;
$data['items'] = $this->{$this->model}->get();
$this->load->view($this->module, $data);
}
and your view
<?php
foreach ($teams as $item):
?>
<div class="col-xs-12">
<?php echo $item->teamname ?>
</div>
<?php
if (isset($arrUsersPerTeam[$item->team_id])) :
foreach ($arrUsersPerTeam[$item->team_id] as $objUser):
?>
<div class="col-xs-12">
<?php echo $objUser->username ?>
</div>
<?php
endforeach;
endif;
endforeach;
You should use a single join query to get your results make sure results are ordered by team
/**model*/
function some func(){
$this->db->select( 'u.username, t.team_id, t.teamname' );
$this->db->from( 'team AS t' );
$this->db->join( 'users AS u', 't.team_id = u.team_id' );
$this->db->order_by( 't.team_id', 'ASC' );
$query = $this->db->get();
return $query->result();
}
In your controller collect results returned by above method defined in your model and pass it to view.
In view there is no need for nested loop only single loop will do the job here like $results contains all the records then in view you can display your records as
/* view */
$parent = false;
$index = 1;
<div class="col-xs-12">
<?php foreach ($results as $result){ ?>
<?php if($parent !=$item->teamname ){ ?>
<?php if($index !=1 ){ ?>
</div>
<?php } ?>
<div class="col-xs-12">
<h2><?php echo $result->teamname ?></h2>
<?php } ?>
<p><?php echo $result->username ?></p>
<?php
$parent =$result->teamname;
$index++;
} ?>
</div> // To close the opened div
2 things: you can pick out key from the foreach, that you can use later, second the "$item" is used 2 places where you might overwrite it by accident.
<?php foreach ($teams as $key => $team_item ): ?>
<div class="col-xs-12">
<?php echo $team_item->teamname ?>
</div>
<?php foreach ($users as $user_item): ?>
<?php if($item->team_id == $key): ?>
<div class="col-xs-12">
<?php echo $user_item->username ?>
</div>
<?php endif ?>
<?php endforeach ?>
<?php endforeach ?>
I'm not really sure if thats what you are trying to achieve
I'm trying to give structure to my code and i am facing a problem.
I'm looping through a sql query response and for each element i'm trying to retrieve other related elements. It works in my controller without problem but when i'm trying to repeat in the view I always get the same value for the related element
My controller:
<?php
include_once('class/guide.class.php');
$bdd = new DBHandler();
$req = guide::getGuides($bdd,0,5);
foreach ($req as $results => $poi)
{
$req[$results]['id'] = htmlspecialchars($poi['id']);;
$req[$results]['name'] = nl2br(htmlspecialchars($poi['name']));
$guide = new guide($results['name'],$bdd);
$guidePois = $guide->getGuidePois($poi['id']);
foreach ($guidePois as $res => $re)
{
echo $guidePois[$res]['id'];
echo $guidePois[$res]['name'];
$guidePois[$res]['id'] = htmlspecialchars($re['id']);
$guidePois[$res]['name'] = nl2br(htmlspecialchars($re['name']));
}
}
include_once('listing.php');
here, you see that I echo the ids/names of the related list of element and it works well, the output is correct for each element of the first list.
When i do it in my view:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>
Somehow the first list output are the good elements, but for the 2nd list, i always get the related elements of the first item.
Do you have an idea ?
Thanks a lot for your help
This is because you only set:
$guidePois = $guide->getGuidePois($poi['id']);
once in the controller.
If you want it to work in the view, you need to insert this code right after the closing </h3>
<?php $guidePois = $guide->getGuidePois($poi['id']); ?>
So that $guidePois gets a new value in each iteration.
Complete view code:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php
$guidePois = $guide->getGuidePois($poi['id']);
foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>
I am trying to get my code to return the last 3 posts from wordpress in Magento using the Fishpig extension. This is the code I have so far, but it appears to returning posts more than once. I also need it to just return posts, as it also returns pages at the moment.
<?php $resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = "SELECT p.id,p.post_title,p.post_name ,p.post_content,p.comment_count,pm.meta_value FROM wp_postmeta AS pm INNER JOIN wp_posts AS p ON pm.post_id=p.ID ORDER BY p.post_date";
$results = $readConnection->fetchAll($query);
?>
<?php
foreach($results as $row) { ?>
<?php if($row['post_title']!='Auto Draft'):
//Get url from pm.meta_value
/********/
$readConnection1 = $resource->getConnection('core_read');
$query1 ="SELECT * FROM `wp_postmeta` WHERE `post_id` = '".$row['meta_value']."' AND meta_key='_wp_attached_file'";
$results1 = $readConnection->fetchAll($query1);
$url='/news/wp-content/uploads/'.($results1[0]['meta_value']);
?>
<div class="blog-post-image">
<img src="<?php echo $url; ?>">
</div>
<div class="blog-post-content">
<?php ?>
<h3> <?php echo $row['post_title'];?></h3>
<p class="blog-content"> <?php $content = $row['post_content']; echo $string = substr($content,0,220); if(strlen($content)>220){echo "...";} ?></a></p>
More Info
</div>
<?php endif; ?>
<?php
if($counter == 4)
{
break;
}
$counter++;
}
?>
To display 3 posts and display the post title, URL, image and post content (or excerpt), you would need the following code:
<?php $posts = Mage::getResourceModel('wordpress/post_collection')
->addIsViewableFilter()
->addPostTypeFilter('post')
->setPageSize(3)
->load() ?>
<?php if (count($posts) > 0): ?>
<ul>
<?php foreach($posts as $post): ?>
<li>
<h2>
<?php echo $this->escapeHtml($post->getPostTitle()) ?>
</h2>
<?php if ($image = $post->getFeaturedImage()): ?>
<img src="<?php echo $image->getAvailableImage() ?>" alt="" />
<?php endif; ?>
<?php echo $post->getPostContent() ?>
<?php
/**
* You could also use:
* echo $post->getPostExcerpt(20)
* This would display the first 20 words of the post content
* or the manually entered excerpt
**/
?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
This has been writte quickly by hand and hasn't been tested but should work fine.
I am working in CodeIgniter framework and I have tried to apply all the other solutions I found on stack but I could not make it work so here is my problem...
I am trying to retrieve a record from MySQL database table called 'questions' based on uri segment. Then I am trying to display this record in a view. As far as I can tell, the uri segment is passed along everywhere it needs to be, and record is retrieved from database.
The problem comes up when I am trying to access the data from the controller, in my view.
Error I am getting for each echo in my loop in 'view_thread_view' is
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/view_thread_view.php
Any solutions would be greatly appreciated.
Here is my code:
Controller thread
function view_thread()
{
$quest = $this->uri->segment(3);
echo $quest;// for checking if uri segment is passed
if($query = $this->data_model->get_thread($quest))
{
$data['records'] = $query;
}
$this->load->view('view_thread_view', $data);
Model data_model
public function get_thread($quest)
{
if($q = $this->db->get_where('questions' , 'qid' , $quest));
{
return $q;
}
}
View view_thread_view
<div title="question_view">
<h1>Question View<h1>
<?php foreach($records as $data) : ?>
<div>
<h2>Title</h2>
<?php
echo $data->title;
?>
</div>
<div>
<h2>Question</h2>
<?php
echo $data->contents
?>
</div>
<div>
<h2>Tags</h2>
<?php
echo $data->tags
?>
</div>
<div>
Thread owner
<?php
echo $records->uname
?>
</div>
<?php endforeach; ?>
</div>
EDIT: QUESTION ANSWERED
Thanks to Girish Jangid fixed the problem this is the working code:
Controller
function view_thread()
{
$quest = $this->uri->segment(3);
echo $quest;// for checking if uri segment is passed
//$data = array();
if($query = $this->data_model->get_thread($quest))
{
$data['records'] = $query;
}
$this->load->view('view_thread_view', $data);
}
Model
public function get_thread($quest)
{
if($q = $this->db->get_where('questions' , array('qid' => $quest)));
{
return $q;
}
}
View
<div title="question_view">
<h1>Question View<h1>
<?php foreach($records->result() as $data) : ?>
<div>
<h2>Title</h2>
<?php
echo $data->title;
?>
</div>
<div>
<h2>Question</h2>
<?php
echo $data->contents
?>
</div>
<div>
<h2>Tags</h2>
<?php
echo $data->tags
?>
</div>
<div>
Thread owner
<?php
echo $data->uname
?>
</div>
<?php endforeach; ?>
</div>
</div>
You should user db function to fetch results, please use CodeIgniter db Query Results functions, like this
if($records->num_rows() > 0){
foreach($records->result() as $data){
if(isset($data->title)) echo $data->title;
}
}
For more detail please read CodeIgniter Query Result function
Query Results
Try this code
<div title="question_view">
<h1>Question View<h1>
<?php if($records->num_rows() > 0) { ?>
<?php foreach($records->result() as $data) : ?>
<div>
<h2>Title</h2>
<?php
echo $data->title;
?>
</div>
<div>
<h2>Question</h2>
<?php
echo $data->contents
?>
</div>
<div>
<h2>Tags</h2>
<?php
echo $data->tags
?>
</div>
<div>
Thread owner
<?php
echo $records->uname
?>
</div>
<?php endforeach; ?>
<?php } ?>
</div>
$records is an array, not an object, therefore you cannot do $records->uname. You probably meant $data there too.
Edit: On second look, it appears $data is an array as well! Arrays are accessed via ['key'] not ->key
Also, your code is way over complicated.
<?php
foreach($records as $data){
$string = <<<STR
<div>
<h2>Title</h2>
{$data['title']}
</div>
...etc
STR;
echo $string;
}
http://www.php.net/manual/en/language.types.string.php
I am retrieving a column from my database and storing that values in an array in my controller.
I am passing that array to the view page, and displaying that values to the user.
All things upto this are working fine.
But the problem is when I am refreshing the page its not showing the values obtained by the controller from the model and just showing blank page..\
I also tried to store the value in a session and use that value but that doesn't seem to work for me.. :(
here is my controller code :-
function full_post_view(){
$data= array(
'ticket_id' => $this->input->post('ticket_id')
);
$this->session->set_userdata($data);
$ticket_id = ($this->input->post('ticket_id')) ? $this->input->post('ticket_id') : $this->session->userdata('ticket_id');
// $post_content = $this->session->userdata('post_content');
echo $ticket_id;
$this->load->model('helpdesk_model');
$all_comments = $this->helpdesk_model->fetchComments($ticket_id);
$is_post_closed = $this->helpdesk_model->fetchPostStatus($ticket_id);
if($all_comments->num_rows > 0) {
foreach ($all_comments->result() as $comments_value) {
$comments = $comments_value->comments;
}
$count=1;
Template::set('all_comments',$all_comments);
Template::set_view('helpdesk/full_post_view');
}
else {
$count=0;
Template::set('post_content',$this->input->post('post_content'));
}
Template::set('is_post_close',$is_post_closed);
Template::set('ticket_id',$ticket_id);
Template::set('is_post_closed',$is_post_closed);
Template::set('post_content',$post_content);
Template::set('count',$count);
Template::set('is_post_closed',$is_post_closed);
Template::render();
}
here is my view :-
<?php $post=Template::get('post_content'); ?>
<?php $ticket_id=Template::get('ticket_id'); ?>
<?php $is_close = Template::get('is_close'); ?>
<h4>Your Problem :- </h4>
<?php echo $post; ?>
<hr/>
<?php foreach ($is_post_closed->result() as $value) {
$is_close = $value->is_close;
} ?>
<?php if(Template::get('count') > 0) : ?>
<?php foreach($all_comments->result_array() as $commentsRow) : ?>
<?php echo word_wrap($commentsRow['comments'],15); ?>
<?php echo " by->"; ?>
<?php echo $commentsRow['username']; ?>
<?php echo $commentsRow['role_name']; ?>
<hr/>
<?php endforeach; ?>
<?php else : ?>
<br/>
No Comments Yet
<?php endif; ?>
<?php if($is_close == 0 ) : ?>
<?php echo form_open('helpdesk/newComment'); ?>
<?php echo form_hidden('ticket_id',$ticket_id); ?>
<?php echo form_hidden('post_content', $post); ?>
<?php echo form_textarea('comment_from_user'); ?>
<?php echo form_submit('submit', 'Comment '); ?>
<?php echo form_close(); ?>
<?php endif; ?>
<?php if($is_close==0) : ?>
<?php echo form_open('helpdesk/closePost'); ?>
<?php echo form_hidden('ticket_id', $ticket_id); ?>
<?php echo form_hidden('post_content', $post); ?>
<?php echo form_submit('submit','close post'); ?>
<?php echo form_close(); ?>
<?php else : ?>
<?php echo form_open('helpdesk/reopenPost'); ?>
<?php echo form_hidden('ticket_id', $ticket_id); ?>
<?php echo form_submit('submit','Reopen post'); ?>
<?php echo form_close(); ?>
<?php endif; ?>
Edit :
I want to ask that how to load the database content again to the view when user refreshes the page.
Edited my Controller and view code
When you refresh the page, do you resend the form ? I'm asking this because from your controller code, it looks like $ticket_id is fetched from _POST and you use pass this variable to the model. If you don't resend the form, the $ticket_id is null and nothing is fetched from DB.
Edit:
Replace in your controller:
$ticket_id = $this->input->post('ticket_id');
with:
$ticket_id = ($this->input->post('ticket_id')) ? $this->input->post('ticket_id') : $this->session->userdata('ticket_id');
and make sure on each request ticket_id exists at least in one from the two possibilities (POST and SESSION)
Solved :)
the problem was when I was refreshing the page, ticket_id was set to 0 and that value was passed as a post .
So the session value was the new ticket_id i.e., 0 and so it was displaying nothing..
I did this:-
if(isset($_POST['ticket_id'])) {
$data= array(
'ticket_id' => $this->input->post('ticket_id'),
'post_content' => $this->input->post('post_content')
);
$this->session->set_userdata($data);
}
$ticket_id =$this->session->userdata('ticket_id');
$post_content =$this->session->userdata('post_content');
i.e., I am storing ticket_id in session when post in set i.e., for the first time. When page is refreshed next time ticket_id post is not set and data is taken from session.