query result using codeIgniter - php

It is the first time for me to use codeIgniter, I tried to build a simple DB driven application.
First the model:
class News_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_news()
{
$query = $this->db->get('news');
return $query->result_array();
}
}
second the controller
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
The view "index":
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
<?php echo $news_item['text'] ?>
</div>
<p>View article</p>
<?php endforeach ?>
When I run the code it displays the header and the footer, but no database record is displayed.
If I put a print statement in the view outside the foreach it works, but not inside the foreach.
I use if($news) to find out if the query retrieved any result, but there is no result retrieved.
How can I know why there is no result retrieved from the DB?

You need to call another foreach inside your foreach. example:
foreach ($result as $row) {
foreach ($row as $key => $val) {
if ($key === "reservation_info") {
$data['decoded'] = json_decode($val);
} else {
$data[$key] = $val;
}
}
}
and i would use the '$val' values in the view. just by calling them as variables, like so
//in the view
echo $decoded
echo $firtname
... and so on

to check if new is empty or not, just
print_r($news);
or you can modify your view :
<?php if(!empty($new)): ?>
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
<?php echo $news_item['text'] ?>
</div>
<p>View article</p>
<?php endforeach ?>
<?php else: ?>
Empty news
<?php endif; ?>

Related

CodeIgniter - joining users, posts, comments tables

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>

fetch data from the database using codeigniter

i have uploaded a image and related content for it in the database, now im trying to fetch it from their and display it on my webpage, but im getting some errors while fetching it
, so please can any one help me where im going wrong? i don know the concept correctly but just how much i know i have implemented it please help me
this is my Home.php(controller)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function __construct()
{
parent::__construct();
//load database libray manually
$this->load->database();
//load Model
$this->load->model('Contact_model');
// load form and url helpers
$this->load->helper(array('form', 'url'));
// load form_validation library
$this->load->library('form_validation');
}
public function Latest_news()
{
$this->form_validation->set_rules('first_content', 'First content', 'required');
$this->form_validation->set_rules('second_content', 'Second content', 'required');
if ($this->form_validation->run()==TRUE)
{
$config['upload_path'] = FCPATH.'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ( $this->upload->do_upload('filename') )
{
//print_r($this->upload->data());die;
$data['first_content'] = $this->input->post('first_content');
$data['second_content'] = $this->input->post('second_content');
$data['filename'] = $this->upload->data('file_name');
//Transfering data to Model
$this->Contact_model->latest_news($data);
//Redirecting to success page
redirect(site_url('Home/Latest_news'));
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);die;
}
}
else
{
$this->load->view('Latest_news');
}
}
public function dispdata_latest_news()
{
$result['data']=$this->Contact_model->displayrecords_latest_news();
$this->load->view('display_records',$result);
}
?>
Contact_model(model)
<?php
class Contact_model extends CI_Model
{
function latest_news($data)
{
//saving records
$this->db->insert('latest_news', $data);
}
//Display
function displayrecords_latest_news()
{
//Displaying Records
$query=$this->db->query("select first_content from latest_news");
return $query->result();
}
}
?>
index.php(view)
<div class="lates">
<div class="container">
<div class="text-center">
<h2>Latest News</h2>
</div>
<div class="col-md-4 wow fadeInDown" data-wow-duration="1000ms" data-wow-delay="300ms">
<img src="<?php echo base_url('images/4.jpg');?>" class="img-responsive" />
<table>
<tr>
<th>Content</th>
</tr>
<?php foreach($query as $r): ?>
<tr><?php echo $r->content; ?>
</tr>
<?php endforeach; ?>
</table>
</div>
Hope this will help you :
Your controller dispdata_latest_news should be like this :
public function dispdata_latest_news()
{
$rows = $this->Contact_model->displayrecords_latest_news();
$result = array('data' => $rows);
/* OR use it like this
$result = ['data' => $rows];
*/
$this->load->view('display_records',$result);
}
Your model displayrecords_latest_news should be like this :
function displayrecords_latest_news()
{
$query = $this->db->get("latest_news");
if ($query->num_rows() > 0)
{
return $query->result();
}
}
Your view should be like this :
<?php
if (! empty($data))
{
foreach($data as $r){ ?>
<tr><?php echo $r->first_content; ?></tr>
<?php }
}
else { ?>
<tr>no record found</tr>
<?php } ?>
I have check your all files and codes and i think you have wrong in your view file.
You have use $r->content. I think where you have get the data in model file the column name is different i.e. first_content.
you have to use like this.
<?php foreach($query as $r): ?>
<tr> <?php echo $r->first_content; ?>
</tr>
<?php endforeach; ?>

Codeigniter foreach whithout $id

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

PHP Error: Trying to get property of non-object

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

Very slow when getting data from class

I have created a class, it store the data from mySQL database into class.
The performance is really slow when outputting to the browser, I have to wait like 10 seconds and this is not acceptable. How to solve this problem?
In the controller file:
$modelCategory = new modelCategory();
$categories = $modelCategory->findAll('takeawayID = :id', array('id' => $takeawayID));
if ($categories === false) {
echo "Query failed";
return;
}
$data['categories'] = $categories;
View File:
<?php foreach ($categories as $category): ?>
<div class="menu-container">
<h2><?php echo $category->name; ?></h2>
<ul class="menu-list">
<?php foreach ($category->item as $item): ?>
<li class="<?php echo $class; ?>">
<div class="menu-holder">
<div class="text-block">
<div class="text-holder">
<?php if ($item->optionsTotal == 1): ?>
<?php foreach($item->options as $option): ?>
<?php $price = $option->price; ?>
<?php $optionvalue = $option->optionValue; ?>
<?php endforeach; ?>
<?php endif; ?>
<h3>
<?php echo $item->name; ?>
<?php if ($item->optionsTotal == 1 && $optionvalue != "Regular"): ?>
(<?php echo $optionvalue; ?>)
<?php endif; ?>
</h3>
<?php if ($item->desc != ""): ?>
<p> <?php echo $item->desc; ?> </p>
<?php endif; ?>
</div>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endforeach; ?>
model Category class file:
<?
class modelCategory extends Model {
public $id;
public $desc;
public $name;
public $items = null;
public function findAll($condition, $parameters) {
$query = "SELECT * FROM categories WHERE " . $condition;
$statement = self::getDb()->prepare($query);
if (!$statement->execute($parameters))
return false;
return self::createModels($statement->fetchAll());
}
public static function createModels($dataAr) {
$models = array();
foreach ($dataAr as $data) {
$category = new modelCategory;
$category->id = $data['id'];
$category->desc = $data['description'];
$category->name = ucwords(strtolower($data['name']));
$models[] = $category;
}
return $models;
}
public function getItems() {
if ($this->items === null)
$this->items = modelItem::find('category_id = :category_id', array('category_id' => $this->id));
return $this->items;
}
public function __get($key) {
switch ($key) {
case 'item':
return $this->getItems();
}
}
}
?>
modelItem:: class is very similar to model Category class.
one problem that I see is that you take the result and build a class to contain the data you could use PDO::FETCH_CLASS that does the same but in a more optimize way.
But like Michael J.V. said you should do some monitoring of your application to detect the exact cause of the problem (there might be multiple and not easy to catch with the eyes)

Categories