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

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

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

call method in controller with parameters

I need to pass parameters to the controller, In the below I have mention a brief explanation with the code,
Controller
class Site2 extends CI_Controller
{
function index()
{
$this->load->helper('url');
$this->home();
}
public function home()
{
$this->load->model('get_company_model');
$this->load->model('bank_account_model');
$data['results'] = $this->get_company_model->get_All();
$this->load->view('view_header');
$this->load->view('view_nav',$data);
$this->load->view('view_content');
$this->load->view('view_footer');
}
in the results array there are id and name,I can get these values in my view, then I need to pass id as parameters and call the function in controller.
view
<?php
foreach($results as $row){
echo $row->id;
//I need to pass this particular id to the function
}?>
You should do it like this:
1) If in same controller:
function home(){
$this->load->model('get_company_model');
$this->load->model('bank_account_model');
$data['results'] = $this->get_company_model->get_All();
$this->some_other_fn_in_same_controller( $data['results'] );
$this->load->view('view_header');
$this->load->view('view_nav',$data);
$this->load->view('view_content');
$this->load->view('view_footer');
}
function some_other_fn_in_same_controller( $results ){
//to do
}
2) If from view:
2.1) Link:
Some Link
2.2) Form: Just put the id in a hidden field and post the form to the controller and get the id in the controller as usual:
<input type="hidden" name="id" value="<?php echo $result['id'] ?>">
$id = $this->input->post('id')

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

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