Display multiple rows in codeigniter - php

I have query where I fetch the content of about 5 rows each with different content, but i dont now to display them individually in my views.
When I pass the the query->result() from my model back to my controller as $query, and then load a view with the $query data, I don't know how to echo out the e.g. content field of row 1.
I only know how to do this: foreach($query as $row) { echo $row->content; }
But this doesn't allow me to select what row content data (out of the 5 retrieved) I wanna echo out.
Could someone please explain how this is done?

The CodeIgniter documentation includes a section titled Generating Query Results which has some examples of what you are looking for.
Here's an (obviously contrived) example:
model:
class Model extends CI_Model
{
public function get_data()
{
return $this->db->query('...');
}
}
controller:
class Controller extends CI_Controller
{
public function index()
{
$data['query_result'] = $this->model->get_data();
$this->load->view('index', $data);
}
}
view:
<?php foreach ($query_result->result() as $row): ?>
<?php echo $row->field_1; ?>
<?php echo $row->field_2; ?>
<?php // and so on... ?>
<?php endforeach; ?>

function a(){
$this->db->select('*');
$this->db->from('table');
$this->db->where(array('batch_id'=>$batchid,'class_id'=>$classid));
$this->db->where(array('batch_id'=>$batchid,'class_id'=>$classid));
$query=$this->db->get();
for($i=1;$i<=$query->num_rows();++$i){
$data[$i]['task'] = $query->row($i)->task;
$data[$i]['subject_id'] = $query->row($i)->subject_id;
$data[$i]['postdate'] = $query->row($i)->postdate;
$data[$i]['cdate'] = $query->row($i)->cdate;
}
}

Related

How to pass result from Model to Controller in CodeIgniter?

I want to get data from the database and display it on a webpage using CodeIgniter. I coded my controller, model and view as follows.
Controller;
//HomeController
<?php
class HomeController extends CI_Controller
{
public function index()
{
$this->load->model('HomeModel');
$data['records'] = $this->HomeModel->getData();
$this->load->view('HomeView',$data);
}
}
?>
Model;
//HomeModel
<?php
class HomeModel extends CI_Model
{
public function getData()
{
$query = $this->db->query('SELECT * FROM data');
return $query->unbuffered_row('object');
}
}
?>
View;
//HomeView
<?php
echo "Recoeds from database<br>";
while($records)
{
echo $records->name." ".$records->age."</br>";
}
?>
But this code doesn't print anything on the screen.(echo "Records from database<br>"; )
So I tried the following code given in the CodeIgniter documentation and echoed the result in the model itself rather than return it to the controller and then to the views.It worked fine.
//HomeModel
<?php
class HomeModel extends CI_Model
{
public function getData()
{
$query = $this->db->query('SELECT * FROM data');
while ($row = $query->unbuffered_row())
{
echo $row->name;
echo $row->age;
}
}
}
?>
My question is how do we return the result of the unbuffered_row() method into the controller and then to the view as per MVC architecture? We can get the output by echoing result at the model itself but it is against the purpose of the MVC architecture.
You should use return $query->result(); and then get the right object in the view or controller (that's up to you).
Try This One
controller
<?php
class HomeController extends CI_Controller
{
public function index()
{
$this->load->model('HomeModel');
$data['records'] = $this->HomeModel->getData();
$this->load->view('HomeView',$data);
}
}
?>
Model
<?php
class HomeModel extends CI_Model
{
public function getData()
{
$data = $this->db->query('SELECT * FROM data');
return array('count'=>$data->num_rows(), 'data'=>$data->result(),'first'=>$data->row());
}
}
?>
View
<?php
echo "Recoeds from database<br>";
foreach($record['data'] as $row)
{
echo $row->name." ".$row->age;
}
?>
I simulated your code in local.Your mistake is here.$records is object .And your while loop has not condition for leaving the loop
<pre>
<?php
var_dump($records);
echo "Recoeds from database<br>";
foreach($records as $value) {
echo $value->name."<br>";
echo $value->age."<br>";
}
?>
</pre>

How to use two tables data in a view in Codeigniter

I have two tables, first table is about topic name and second table shows sub-topics. I want to show from first table topic name then search their corresponding sub-topic and show it in view and so on till topic names are found in first table. But the problem is i can only get one table data in view i.e. main topic table. I have no idea how to get full data of both table and use it.
Database Structure:
Model:
<?php
class Topics_Model extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_all_topics()
{
$this->load->database();
$this->db->select("*");
$this->db->from("topics");
$query=$this->db->get();
return $query->result();
}
}
?>
Controller :
<?php
class drag_drop_course_material extends CI_Controller {
function drag_drop_course_material()
{
parent::__construct();
}
function index()
{
$this->load->model('topics_model');
$data['query']=$this->topics_model->get_all_topics();
$this->load->helper('url');
$this->load->view('drag_drop_course_material', $data);
}
}
?>
View:
<?php
foreach ($query as $row) {
?>
<li> $row->topic_name </li>
<? } ?>
Required Output:
Try this query. We do left join of both tables.
$CI->db->select('*');
$CI->db->from('topic');
$CI->db->join('sub-topics', 'topic.id = sub-topics.sub_topic_id', 'left');
$query = $CI->db->get();
$result = $query->result();
You will get result in your model. return this result from model and access it in controller. Once you print return result in controller you will get idea that how to render it because you already did it above.
Your controller is perfect, your model is perfect just change your view:
In view:
foreach ($query as $row)
{ ?>
<ul>
<li><?php echo $row['topic_name'];?>
<ul>
<?php $this->db->where('sub_topic_id',$row['id'])
$r = $this->db->get('subtopics');
if($r->num_rows()>0)
{
foreach ($r -> result_array() as $row) {
$data1[] = $row;
}
}
foreach($data1 as $sub){?>
//print <li><?php echo $sub['subtopic_name']?></li>
<? }?>
</ul>
</li>
<? }?>
</ul>

How to pass a value from view to model in Code Igniter

I want to edit retrieved users that am stuck here is my code
I have a function in the model that selects all the users
public function retrieve() {
$this->db->select('*');
$query = $this->db->get('UserDetails');
return $query->result();
}
In the controller the queried data is passed to view
public function edit_user() {
$data['query']=$this->user_model->retrieve();
$this->layout->view('creation/update_user',$data);
}
Like this
<?php foreach($query as $row): ?>
<?php echo $row->username;?>
<?php echo $row->firstname;?></a>
<?php endforeach;?>
I want when one clicks on the username he should be able to edit the user.
How do i get the value of the clicked username that will be passed to the
$username
in the model (am aware CI is MVC, how can pass to controller then to model)
public function select_user_details() {
$this->db->select('*');
$this->db->where('username' $username);
$query=$this->db->get('users');
return $query->result();
}
In the controller for editing users
public function edit_user() {
$data['query']=$this->user_model->select_user_details();
$this->layout->view('creation/update_user',$data);
}
In the display
<? foreach($query as $row)
<input type="text" name="uname" value="<?php echo $row->username; ?>"/>
<input type="text" name="name" value="<?php echo $row->names; ?>"/>
<?php endforeach; ?>
You can add a parameter to the edit user method, and make a redirection in your controller. So, if there's no id specified, you get the list of all users, but if there is an id, you run a new model function (query with WHERE user_id = $id rather than $username) and load another view. Something like this:
public function edit_user($id = false) {
if ( !$id ) {
$data['query']=$this->user_model->retrieve();
$this->layout->view('creation/update_user',$data);
}
else {
$data['query']=$this->user_model->retrieve_one_user($id); // new model method for a single user
$this->layout->view('creation/edit_user',$data); // new view
}
}
And in your view, you need to make your username link go to .../edit_user/USER_ID_HERE.
You can also use different controller methods for that: like list_users() and edit_user($id). Also, you can do it in a single view. It's really up to you and what will work best for your app. There are million ways to do it.
To do it with the least amount of changes, just add a parameter to the select_user_details method (as well as the edit_user method in the controller):
public function select_user_details($username) {
...
public function edit_user($username) {
...
But again, make sure that the link from the user list would go to .../select_user_details/my_username_here. Like this:
<?php echo $row->username;?>
In View -
<?php foreach($query as $row): ?>
<?php echo $row->username;?>
<?php echo $row->firstname;?></a>
<?php endforeach;?>>
In Controller -
function edit_user($userName)
{
$data['query']=$this->user_model->retrieve($userName);
$this->layout->view('creation/update_user',$data);
}
In Model -
public function retrieve($userName) {
$this->db->select('*');
$query = $this->db->get('UserDetails');
return $query->result();
}

CodeIgniter limit posts per page

I am creating a blog with CodeIgniter. My homepage shows posts that are coming from the database. I want to limit the posts for a page and create a link at the bottom to bring the next posts.
Please someone teach me how to do it with some example.
Thanks.
controller code
<?php
class Mysite extends CI_Controller
{
function index()
{
$this->load->model('posts_model');
$data['result']=$this->posts_model->getAll();
$this->load->helper('html');
$this->load->view("header");
$this->load->view("home",$data);
$this->load->view("footer");
}
?>
model code
<?php
class Posts_model extends CI_Model{
public function getAll(){
$this->load->database();
$query = $this->db->get('posts');
return $query->result();
}
}
?>
view code
<?php
foreach($result as $row) {
$a_url="mysite/single/".$row->id;
echo "<div id="."'postdiv'".">";
echo "<h1>".anchor($a_url,$row->title)."</h1>";
echo "<p>".$row->content."</p>";
echo "<p>Posted by : ".$row->author."</p>";
echo "<br>";
echo "</div>";
}
?>
Here is a nice blog showing load more pagination using jquery and codeigniter.
http://www.thetutorialblog.com/php/twitter-like-pagination-using-codeigniter-and-jquery/
Sample code. Try yourself
function getcountryByname($limit=NULL, $start=NULL) //select country
{
if($limit!=NULL) $this->db->limit($limit, $start);
$this->db->select('*');
$this->db->from('country');
$this->db->order_by("country_name", "ASC");
$query = $this->db->get();
return $query->result_array();
}

How to show category name in Product Page in Codigniter?

I have two table in database ::: 1. tbl_category 2. tbl_product.
Showing all category list in home page and when user clicks on signle category then it goes to product page(from tbl_product) by category id (included category id in tbl_product)
Issue ::: I want to show the category Name and Image Here. So that user can see in which category they clicked on (from tbl_category ) ::: how can I get them ??? please help me
Controller ::::
class Home extends CI_Controller{
//put your code here
public function __construct() {
parent::__construct();
$this->load->model('home_model');
}
public function index(){
$data=array();
$data['result']=$this->home_model->selectCategory($config['per_page'], $this->uri->segment(3));
$data['maincontent']=$this->load->view('home_message',$data,TRUE);
$this->load->view('home', $data);
}
public function category($category_id){
$data=array();
$data['result']=$this->home_model->selectProductByCategoryId($category_id);
$data['maincontent']=$this->load->view('category_detail',$data,TRUE);
$this->load->view('home', $data);
}
Model::::
class Home_Model extends CI_Model{
//put your code here
public function selectCategory($per_page, $offset)
{
$this->db->select('*');
$this->db->from('tbl_category');
$this->db->order_by("category_id", "desc");
$query = $this->db->get('', $per_page, $offset);
foreach ($query->result() as $row)
$data[] = $row;
return $data;
}
public function selectProductByCategoryId($category_id)
{
$this->db->select('*');
$this->db->from('tbl_product');
$this->db->where('category_id',$category_id);
//$this->db->order_by("product_id", "desc");
$query_result= $this->db->get();
$result=$query_result->result();
return $result;
}
View::::
I want to show the category Name and Image Here. So that user can see in which category they clicked on ::::
<?php
foreach ($result as $values)
{
?>
<div>
<div>
<img src="<?php echo base_url();?><?php echo $values->product_image ?>" width="90%" height="220" />
</div>
<div>
<b><?php echo $values->product_name ?></b> <br>
<b>Price: <?php echo $values->product_price ?></b> <br>
Order Now
</div>
</div>
<?php } ?>
Controller
public function category($category_id){
$data=array();
$data['result'] = $this->home_model->selectProductByCategoryId($category_id);
// Added this line
$data['category'] = $this->home_model->selectCategoryByd($category_id);
$data['maincontent'] = $this->load->view('category_detail',$data,TRUE);
$this->load->view('home', $data);
}
Model_Home
public function selectCategoryById($category_id)
{
$result = $this->db->select('*')
->from('tbl_category')
->where('id',$category_id)
->get()
->result();
return $result;
}
Then echo some of those in your view.
You are using a Model_Home for other models functions?
Models are for data and everything what has to do with that data. You should have a Model_Category with a selectById function and a Model_Product with a selectByCategoryId AND a selectById function. Models are NOT used to describe pages.
Please read about MVC and CodeIgniters implementation of it. Then refactor your code and properly use codeigniters features which, if implemented correctly, allow you to not even have to write these functions yourself! Note: I do not know CI very well, so I don't know about the specific implementations of e.g. MVC, ORM, and the like

Categories