how to pass two result in same view in codeigniter - php

i am new with codeigniter.I have written controller,model.view.
I want to execute the another query in the model which having the "ID" from first model query in the where condition and pass the seperate results for both the both query in same view.
i have explain it in model and view.
how can i do this.need some syntax how can i do this.
or is this correct way or do somwthing??
Controller
class demo extends CI_Controller
{
function getRecords()
{
$offset = trim($this->input->get('off'));
$this->load->model('demo_model');
$data = $this->demo_model->get_messages($offset);
$return = $this->load->view('demo_view',array('records'=>$data),true);
die($return);
}
}
Model
class demo_model extends CI_Model
{
function get_messages($offset = 0)
{
$q = $this->db->query(" select Id,cloum2 from table");
// want to use ID from above query in to second query
// Like sql="select * from table where id='$id'" ;
// and how i pass the separate result for both query inthe view
return $q->result_array();
}
}
View demo_view;
<?php foreach($records as $row) :?>
<div> do something with $row </div>
<div> //want use second query foreach here </div>
<?php endforeach ;?>

Both queries will return PHP arrays so you can do something like.
MODEL
function get_messages($offset = 0)
{
$q = $this->db->query(" select Id,cloum2 from table");
return $q->result_array();
}
function get_id($id){
$q = $this->db->query("select * from table where id='$id'");
return $q->result_array();
}
CONTROLLER
class demo extends CI_Controller{
function getRecords(){
$offset = trim($this->input->get('off'));
$this->load->model('demo_model');
$data = $this->demo_model->get_messages($offset);
for($c=0;$c<count($data);$c++){
$data[$c]['innerRow']=$this->demo_model->get_id($data[$c]['id']);
}
$return = $this->load->view('demo_view',array('records'=>$data),true);
die($return);
}
VIEW
<?php foreach($records as $row) :?>
<div> do something with $row </div>
<div>
<?php foreach($row['innerRow'] as $innerrow) :?>
......
<?php endforeach ;?>
</div>
<?php endforeach ;?>
(But this isn't such a good idea as you will run a bunch of queries to the model. Its better to think of a nicer query)

function getRecords()
{
$offset = trim($this->input->get('off'));
$this->load->model('demo_model');
$data = $this->demo_model->get_messages($offset);
$secresult=array();
foreach($data as $msg)
{
$res = $this->demo_model->get_result($msg['id']); // pass id to query
$secresult[]=$res;
}
$return = $this->load->view('demo_view',array('records'=>$data, 'theresult'=>$secresult),true);
die($return);
}
In your view file, you can use theresult for the second loop.

Related

Select and display all rows in Codeigniter

I'm novice in Codeigniter framework and I want to ask if is good or it exist another method to display all rows from database in view page.
I have this controller:
class Dashboard extends CI_Controller{
public function index()
{
$data['user'] = $this->dashboard_model->get_user_details($this->session->userdata('logged_in'));
$this->load->view('includes/header', $data);
Model dashboard:
class Dashboard_model extends CI_Model{
public function get_user_details($user_id){
$this->db->select("*");
$this->db->where('id', $user_id);
$result = $this->db->get('users');
return $result->result_array ();
}
}
And I display in view page like:
<?php echo $user[0]['id']; ?>
<?php echo $user[0]['username']; ?>
Code is working, it show me what I want but I don't know if this is a good solution.
You can also use return $result->row_array (); if it returns only single row.
and then in your view file get the data by using : $user['id'];
for multiple rows :
your solution is fine but you need to add foreach loop and get the data
ex:
foreach($user as $usr) {
echo $usr['id']; echo "<br/>";
echo $usr['username'];
}
By applying $this->db->where('id', $user_id); you will only get results (1) for the user with $user_id (not all users) and (2) you will only get results if a user with that id exists in the database. The correct way to get all users, while slightly modifying your function to support returning only one user is as follows:
/**
* #param int $user_id When NULL will return all users
* #return array
*/
public function get_user_details($user_id = null) {
$this->db->from('users');
if (!is_null($user_id)) {
$this->db->where('id', $user_id);
$q = $this->db->get();
if ($q->num_rows() !== 1) {
return array();
}
return $q->row_array();
} else {
return $this->db->get()->result_array();
}
}
So to get all users: $this->dashboard_model->get_user_details()
To get logged in user: $this->dashboard_model->get_user_details($this->session->userdata('logged_in'))
To get a user with id 123: $this->dashboard_model->get_user_details('123')
When $user_id is blank you can go through results like:
if (count($users) !== 0) {
foreach ($users as $user) {
echo $user['id'];
echo $user['username'];
}
} else {
echo 'No users';
}
When $user_id is set you get a single result thus this will work:
if (count($users) !== 0) {
echo $users['id'];
echo $users['username'];
} else {
echo 'User with that id does not exist!';
}
For single user information I would use row_array() or row()
https://www.codeigniter.com/userguide3/database/queries.html
<?php
class Dashboard_model extends CI_Model{
public function get_user_details($user_id){
$this->db->where('id', $user_id);
$result = $this->db->get('users');
return $result->row_array();
}
}
Controller
<?php
class Dashboard extends CI_Controller {
public function index()
{
$this->load->model('dashboard_model');
// Use the users id stored in your session when logged in
$userinfo = $this->dashboard_model->get_user_details($this->session->userdata('id'));
$data['id'] = $userinfo['id'];
$data['username'] = $userinfo['username'];
$this->load->view('includes/header', $data);
}
}
Then echo on view
<?php echo $username;?> example <?php echo $id;?>
Updated answer : As per details provided in commnets
instead of return $result->result_array(); use return $result->row_array();
View :
<?php echo $user['id']; ?>
<?php echo $user['username']; ?>
For fetching multiple rows :
return $result->result_array(); will give you array of all the users present in users table.
What you need to do is, access those users in view page using foreach loop.
<?php
foreach ($user as $row) {
echo $row['id'];
echo $row['username'];
}
?>
In your MODEL
class Dashboard_model extends CI_Model{
public function get_user_details($user_id){
return this->db->get_where('users', array('id' => $user_id))->result_array(); //You can use result_array() for more than one row and row_array() only for one row
//If you want to show all rows form database use this return $this->db->get('users')->result(); OR result_array()
}
}
In your View
For more than one row use foreach loop
foreach($user as $usr){
echo $usr['']; //Add all your database data here like this
}

Getting Error : Trying to get property of non object

I am a beginner in the CodeIgniter. Working on one small basic project, while I am working on the List view I get an error " Trying to get property of non-object.
Please help me!
Here the screen shots.
Error
My code
Here is my view :
<ul id="actions">
<h4>List Actions</h4>
<li> Add Task</li>
<li> Edit List</li>
<li><a onclick="return confirm('Are you sure?')" href="<?php echo base_url();?>lists/delete/<?php echo $list_detail->id;?>"> Delete List</a></li></ul>
<h1><?php echo $list_detail->list_name; ?></h1>
Created on : <strong><?php echo date("n-j-Y",strtotime($list_detail->create_date)); ?></strong>
<br/><br/>
<div style="max-width:500px;"><?php echo $list_detail->list_body; ?></div>
<!-- <?php //echo print_r($query); ?>
-->
<br/><br/>
Here is Controller
public function show($id){
$data['list_detail'] = $this->List_model->get_lists($id);
$data['main_content']='lists/show';
$this->load->view('layout/main',$data);
}
Here is model
public function get_list($id){
$query=$this->db->get('lists');
$this->db->where('id', $id);
return $query->row();
}
This error is generating because you are trying to access an array in class object style.
Ex:
$data['list_details'] = 'some value';
and accessing it like:
$data->list_details; // it will generate the error "Trying to get property of non object"
After viewing your code. I think you have written wrong in your model function
Your model function must be like below
public function get_list($id) {
$this->db->where('id',$id);
$query = $this->db->get('lists');
return $query->row();
}
Also in your view before you print the value please check it with the condition of !empty($list_details). so if value is not there still it will not throw any error.
I hope this will help you.
From your controller you are calling the model function as get_lists().
But there is no function as get_lists in model. U need to change the function name in controller to get_list()
When your using $query->row() on your model function then on controller
Model Function
public function get_list($id) {
$this->db->where('id',$id);
$query = $this->db->get('lists');
return $query->row();
}
Controller
public function show($id){
// Gets data where it belongs with that id
$list_data = $this->model_name->get_list($id);
$data['id'] = $list_data->id;
$data['create_date'] = $list_data->create_date;
$data['list_body'] = $list_data->list_body;
$this->load->view('someview', $data);
}
When your using $query->row_array(); on your model function then on controller
public function get_list($id) {
$this->db->where('id',$id);
$query = $this->db->get('lists');
return $query->row_array();
}
Controller
public function show($id) {
// Gets data where it belongs with that id
$list_data = $this->model_name->get_list($id);
$data['id'] = $list_data['id'];
$data['create_date'] = $list_data['create_date'];
$data['list_body'] = $list_data['list_body'];
$this->load->view('someview', $data);
}
On view then you can access
<?php echo $id;?>
<?php echo $create_date;?>
<?php echo $list_body;?>
Update for multiple data
public function get_list() {
$query = $this->db->get('lists');
return $query->result();
}
Controller
$results = $this->model_name->get_list();
// Or
//$results[] = $this->model_name->get_list();
$data['list_detail'] = $results;
$this->load->view('someview', $data);
View
<?php foreach ($list_detail as $list) {?>
<?php echo $list->id;?>
<?php echo $list->create_date;?>
<?php echo $list->list_body;?>
<?php }?>

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>

foreach not working in codeigniter

I am currently new to database query and other for codeigniter can not seem to quite get model working for what I am after.
I have tried loading db in direct to controller and that works OK. But if I call my model does not want to work nothing shows up.
Here is what I would like to achieve.
Controller
public function website_test_model() {
$this->load->model('admin/website/model_website');
$results = $this->model_website->getWebsites();
$data['websites'] = array();
foreach ($results as $result) {
$data['websites'] = array(
'website_id' => $result['website_id'],
'name' => $result['name'],
'url' => $result['url']
);
}
$this->load->view('website/websites', $data);
}
View
<!-- Not Working From Controller Function Model Test -->
<?php if ($websites) { ?>
<?php foreach ($websites as $website) { ?>
<?php echo $website['website_id'];?>
<br>
<?php echo $website['name'];?>
<br>
<?php echo $website['url'];?>
<?php } ?>
<?php } ?>
Model
<?php
class Model_website extends CI_Model {
function getWebsites() {
$this->db->select('*');
$this->db->from('website');
$this->db->where('website_id');
$this->db->where('name');
$this->db->where('url');
$query = $this->db->get();
if($query->num_rows() > 0) {
return $query->row();
} else {
return false;
}
}
}
Codeigniter Demo It works when I try it this way as said on codeigniter User Guide. Just the code above is way I am after though Trying to make model work no luck
public function website() {
$results = $this->db->get('website'); // Works Direct From Controller OK.
foreach ($results->result() as $row) {
$data = array(
'website_id' => $row->website_id,
'name' => $row->name,
'url' => $row->url
);
}
$this->load->view('website/website', $data);
}
you are doing wrong in you model file
<?php
class Model_website extends CI_Model {
function getWebsites() {
$query =$this->db->get('website');
if($query->num_rows() > 0) {
return $query->result();
}
}
}
1) In your model you are using where condition but $this->db->where('website_id'); but you not passing anything in your condition you have to do like this $this->db->where('website_id',$yourwebsite_id);
You have to check db query in model it's return result or not.
use this query in model
$this->db->last_query();
Use this query in model
$query = $this->db->get('website');
return $query;
Pass this query to view then use this foreach
foreach ($query->result() as $row)
{
<?php echo $row->website_id; ?>
<br>
<?php echo $row->name;?>
<br>
<?php echo $row->url;?>
}

Display multiple rows in codeigniter

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;
}
}

Categories