Select and display all rows in Codeigniter - php

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
}

Related

how to get specific value from db and show result in view codeigniter

i have problem to show my query result in my view, i user codeigniter with mvc structure, in model my code its look like this,
<?php
class Model_Kabalitbang extends CI_Model{
public function getPaguAnggaran(){
$query = "SELECT pagu_anggaran_program_modalutama FROM program_modal_utama WHERE id_program_modalutama = '3'
";
return $this->db->query($query);
}
}
and in my controller i call my model like this
<?php
class Kabalitbang extends CI_Controller{
function __construct(){
parent::__construct();
if($this->session->userdata('logged_in') !== TRUE){
redirect('login');
}
$this->load->model('Model_Kabalitbang');
}
function index(){
//Allowing akses to kabalitbang only
if($this->session->userdata('level')==='2'){
// Jumlah PAGU
$pagu = $this->Model_Kabalitbang->getPaguAnggaran();
$paguanggaran = $pagu->num_rows();
$data = array(
'jml_pagu' => $paguanggaran,
);
$this->load->view('kabalitbang/dashboard_view', $data);
}else{
echo "Access Denied";
}
}
}
but when i call in view <?=$jml_pagu ?> this show just 1, but the value form field in my query is 24392
how to make my code run?
Your query is already return a row containing a number, so you just need to display the row, not counting the row again :
$pagu = $this->Model_Kabalitbang->getPaguAnggaran();
$paguanggaran = $pagu->row_array();
$data = array(
'jml_pagu' => $paguanggaran['pagu_anggaran_program_modalutama'],
);
use this...
$this->db->where('id_program_modalutama ',3);
$result['data']=$this->db->get('Table Name')->result();
$this->load->view('kabalitbang/dashboard_view', $result);
now use loop on $data in your view...
Example :-
foreach($data as $allData)
{
print_r($allData);
}

I want to get max id value from table in codeigniter

in model file i write this code:
public function maxcode()
{
$this->db->select (max(ClassID)+1 as ClassID)-> from ('class');
$query=$this->db->get();
if($query->num_rows>0)
{
$row = $query->row_array();
return $row;
}
echo $row['ClassID'];
}
in controller function i write.....this code
public function maxcode()
{
$this->insert->maxcode();
}
Now I understand what your problem is.
You need to transfer this value to the template. This is done in the page controller
Example
$data['ClassID'] = $this->insert->maxcode();
$this->view('tenplate Name', $data);
And used in template
<?php echo $ClassID; ?>

How to get all the data from database in session after getting logged-in in CodeIgniter?

I want to display all the data of a user from db by using session.
<?php
class login_model extends CI_model
{
function Can_login($email,$password)
{
$this->db->select('*');
$this->db->where('email',$email);
$this->db->where('password',$password);
$query = $this->db->get('registration');
if($query->num_rows() > 0)
{
return true;
}
else
{
return false;
}
}
}
?>
You should return actual data from model function
<?php
function Can_login($email,$password)
{
$query = $this->db
->where('email',$email)
->where('password', $password)
->get('registration');
if($query->num_rows() > 0)
{
return $query->result(); //or result_array() or other type
}
return false;
See documentation on Generating Query Results for details on the types of returns available.
You can do it the way you are doing it above but with a few changes
<?php
class login_model extends CI_model
{
function Can_login($email,$password)
{
$user = $this->db->select('*')
->where(['email'=>$email, 'password'=>$password])
->get('registration')->row();
//dont need to check for row, if user is not found it will be empty and trigger false part of your statement
//could even just return user in general and do this logic in controller
if($user)
{
$_SESSION['user'] = $user
return true;
}
else
{
return false;
}
}
}
?>

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 do I display active record in codeigniter with multiple controllers?

I am building my comment module and trying to get the active records to display on view. Seems simple however I have a lot going on and using a separate model and controller then what the view is being generated from.
So I have a profile page ( where I'm trying to get the results to display )
Controller:
public function profile()
{
$this->load->helper('url'); //Include this line
$this->load->helper('date');
$this->load->library('session');
$this->load->library('form_validation');
$session_id = $this->session->userdata('id'); //Ensure that this session is valid
//TRYING TO MAKE A VARIABLE WITHT THE $_GET VALUE
$user_get = $this->uri->segment(3); // Modify this line
// LOAD THE CORRECT USER
$this->load->model('account_model');
$user = $this->account_model->user($user_get); //(suggestion) you want to pass the id here to filter your record
$data['user'] = $user;
$data['session_id'] = $session_id;
if($user_get != $user['id'] || !$user_get)
{
$data['main_content'] = 'account/notfound';
$this->load->view('includes/templates/profile_template', $data);
}
else
{
if($user_get == $session_id) //Modify this line also
{
$data['profile_icon'] = 'edit';
}
else
{
$data['profile_icon'] = 'profile';
}
$sharpie = $this->sharpie($user);
$data['sharpie'] = $sharpie;
$data['main_content'] = 'account/profile';
$this->load->view('includes/templates/profile_template', $data);
}
}
Now I have a new controller for my comments I'm trying to display:
public function airwave() {
$this->load->helper('date');
$this->load->library('session');
$airwave_get = $this->uri->segment(3);
$this->load->model('community_model');
$airwave = $this->coummunity_model->airwave($airwave_get);
$data['airwave'] = $airwave;
$data['main_content'] = 'account/profile';
$this->load->view('includes/templates/main_page_template', $data);
}
with this model:
public function airwave($id=null)
{
if(is_null($id)) {
$session = $this->session->userdata('is_logged_in');
$commenter_id = $this->session->userdata('id');
}else{
$commenter_id = intval($id);
}
$query = $this->db->query("SELECT * FROM airwaves_comments WHERE from_id=$commenter_id");
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data[0];
//above returns the single row you need to the controller as an array.
//to the $data['user'] variable.
}
}
and trying to display it on this view ( which is generated by the profile function )
<div class="profile_airwave_comment_text">
<?php echo $airwave['comment'];?>
</div>
I just can't seem to get it to pass the array variable I've created properly to that view?
thanks in advance.
The first glaring thing I see wrong is in you model's airwave function:
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data[0];
You are assuming that there will only be one result in your query, so if there are more or less than one, your $data array will bever be set.
Also, even then you are only returning the first element in the array. I am not seeing anywhere in your question that you want to return only one.
Finally, in your view, if you now return the full array, and not only one element, you will have to do a foreach statement.
EDIT: please see suggested solution.
In your model, don't worry about the check for the amount of data in the result array. This will come later. Simply do:
return $query->result_array();
Now, keep your controller as is, but adapt your view:
<div class="profile_airwave_comment_text">
<?php
if (isset($airwave) && is_array($airwave) && !empty($airwave))
{
foreach ($airwave as $wave)
{
echo $wave['comment'];
}
}
else
{
echo 'No comments found...';
}
?>
</div>
This should work, and if not, at least let you know that no comments were fond, and thus check your database.
HTH!
If your using HMVC, simply call the module from inside the profile view, ie:
echo Modules::run('comments/profileComments', $user->id);
Else:
You would need to create a new method in the loader class, to load in the controller seperate from routing.
If your really after a quick fix until you come up with a better alternative, you could(depending if both controllers live in the same directory) just include the 'comments' controller in your 'profile' controller and try something like this:
{Cons: CI Pagination wont work!}
application/controllers/profile.php
include 'Comments' . EXT;
class Profile extends CI_Controller{
public function __construct ()
{
parent::__construct () ;
}
public function index( $user_id ){
$commentsPartialView = call_user_func_array(array(new Comments(), "getProfileComments"), array($user_id));
return $this->load->view($this->template, array(
'view' => 'profiles/_index',
'comments' => $commentsPartialView
));
}
}
-
application/controllers/Comments.php
class Comments extends CI_Controller{
public function __construct ()
{
parent::__construct () ;
}
public function getProfileComments( $user_id ){
$user_comments = ''; //pull from DB
//set third param to TRUE for partial view, without main template
return $this->load->view('comments/show', array(
'user_comments' => $user_comments
), TRUE);
}
}

Categories