How to pass $data from CodeIgniter's controller to model? - php

Im trying to allow a user to edit their own details. Here is my code:
Controller:
public function myaccount() {
if($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$data['id'] = $session_data['id'];
$this->load->model('myaccount_model');
$this->myaccount_model->get_details($data);
$this->load->view('head');
$this->load->view('myaccount', $data);
$this->load->view('footer');
} else {
redirect('login', 'refresh');
}
}
Model:
<?php
class Myaccount_model extends CI_Model {
public function __construct() {
$this->load->database();
}
public function get_details($data) {
$query = $this->db->get_where('users', array('id' => $id));
return $query->row_array();
}
}
It comes up with the error :Undefined variable $id on my account_model. The session is created at the controller as:
$data['id'] = $session_data['id'];
So how do i pass the data from the controller, to the model so i can query the database and select the user that matches the session id? Thanks

Use $data['id'] because you are setting the value in your controller
public function get_details($data)
{
$query = $this->db->get_where('users', array('id' => $data['id']));
return $query->row_array();
}
In order to echo out user data in your view I think you can do something like this:
$userData = $this->myaccount_model->get_details($data);
$this->load->view('myaccount', $userData);

there is no variable at your model $id inside get details function.
try to change your getdetails function like this
public function get_details($data)
{
$query = $this->db->get_where('users', array('id' => $data['id']));
return $query->row_array();
}
Or you can pass only id instead of $data like this from your controller
$this->myaccount_model->get_details($session_data['id']);
Now you can change your model like this
public function get_details($id)
{
$query = $this->db->get_where('users', array('id' => $id));
return $query->row_array();
}

Related

Codeigniter Model returning empty data

I have a problem with my model. It's returning empty data.
Here is the controller.
public function getReport() {
$data = array();
$id = $this->input->post('id');
$this->auth->setId($id);
$data['instant_main']=$this->auth->getReportData();
$this->load->view('auth/report-item', $data);
}
and this is my Model
class Auth_model extends CI_Model {
// Declaration of a variables
private $_id;
public function setId($id) {
$this->_id = $id;
}
function getReportData()
{
$this->db->select('*');
$this->db->from('inbound_main');
$this->db->join('inbound_item', 'inbound_main.id = inbound_item.report_id');
$this->db->where('inbound_item.report_id', $this->_id);
$query = $this->db->get();
return $query->result();
}
}
If I have removed the WHERE condition from the query, everything was fine.
Your $this_id is empty..
You have folow the code like this
Controller
$data['instant_main']=$this->auth->getReportData($id);
Model
function getReportData($id)
{
$this->db->select('*');
$this->db->from('inbound_main');
$this->db->join('inbound_item', 'inbound_main.id = inbound_item.report_id');
$this->db->where('inbound_item.report_id', $id);
$query = $this->db->get();
return $query->result();
}

How obtain directly the model from a query? -> CodeIgniter

Can I obtain the model directly from a query in Code Igniter?
Model
<?php
class User_Model extends CI_Model {
public $user_id;
public $name;
public $team_id
public function getTeamName() {
$this->db->select('name');
$this->db->from('team');
$this->db->where('team_id',$this->team_id);
$query = $this->db->get();
$team = $query->row();
if($empresa == null){
return "";
} else {
return $team->name;
}
}
public function getUser($id) {
$query = $this->db->get_where('users', array('user_id' => $id));
$user = $query->row();
return $user;
}
I would like getUser($id) function returns a user object like 'new User_Model()' to be able to use getTeamName() function in the view. Can I do it?
Now returns an object, but not a User_Model() object.
is wrong call a method in the model from the view.
in the model use
function getUser($id){
$query = $this-db->select('*')
->from('users')
->where('user_id', $id)
->get();
return $query->result();
}
this return a object with all data, then you call the method in the controller like this
$data['user_model'] = $this->model_name->getUser($id);
$this->load->view('Your_View',$data);
then in the view $user_model is the object
in the view
print_r($user_model);
As long as the model is loaded, in your view you can access any public function or property like:
$this->user_model->getUser() or $this->user_model->team_id
View:
<?php
echo $this->user_model->getUser(1)->username;
This is against MVC in some respects but I can understand the logic behind doing so based on the following scenario where you want to say use num_rows and result without doing count:
class User_Model extends CI_Model {
public function getUsers() {
return $this->db->get('users');
}
}
class Some_Controller extends CI_Controller {
public function index() {
$this->load->model('user_model');
$data['users'] = $this->user_model->getUsers();
$this->load->view('some_view', $data);
}
}
View:
<?php
if ($users->num_rows() > 0) {
foreach ($users->result() as $row) {
echo $row->username;
}
} else {
echo 'No users';
}
Actually there is another possibility you can use
create a Team_model and an User_model
The Team_model could look like
class Team_model extends CI_Model
{
$arrTeamNames = [];
public function getTeamName($team_id)
{
if (!isset($this->arrTeamNames[$team_id]))
{
$query = $this->db
->select('name')
->from('team')
->where('team_id',$this->team_id)
->get();
if ($query->num_rows() == 1)
{
$objTeam = $query->row();
$this->arrTeamNames[$team_id] = $objTeam->name;
return $objTeam->name;
}
return '';
}
return $this->arrTeamNames[$team_id];
}
}
and the User_model
class User_Model extends CI_Model
{
public function getUser($id)
{
$query = $this->db->get_where('users', array('user_id' => $id));
if ($query->num_rows() == 1)
{
$user = $query->row(0, 'User_Object');
return $user;
}
}
}
class User_Object
{
public function getTeamName()
{
$ci = get_instance();
$ci->load->model('Team_model');
return $ci->team_model->getTeamName($this->team_id);
}
}
Note in the User_model you have an additional User_Object which
gets mapped by the row() function which is well documented
here.
Now if you call this model in one of your controller and pass it to your view you actually can access to a model function in a proper way e.g.
class User extends CI_Controller
{
public function detail($user_id)
{
$this->load->model('User_model');
$objUser = $this->User_model->getUser($user_id);
$this->load->view('user-detail', ['objUser' => $objUser]);
}
}
//user-detail view
echo $objUser->getTeamName();

How to pass Codeigniter controller array to view and use foreach function?

I can't access codeigniter controller array values in the view. where did i miss.
mymodel
function get_data(){
$this->db->select('prod_id, content, details');
$query = $this->db->get('tblesample');
return $query->result();
}
controller
public function index(){
$this->load->model('mymodel');
$user_info = $this->mymodel->get_data();
$this->load->view('inc/header_view');
$this->load->view('data_view', $user_info);
}
data_view
<div class="col-md-9">
<?php
foreach ($user_info as $info) {
echo $info->content;
}
?>
</div>
In controller change the code.
public function index(){
$this->load->model('mymodel');
$data['user_info'] = $this->mymodel->get_data();
$this->load->view('inc/header_view');
$this->load->view('data_view', $data);
}
You be better off using associative array to pass on to the view:
public function index(){
$this->load->model('mymodel');
$data = [
'user_info' => $this->mymodel->get_data(),
];
$this->load->view('inc/header_view');
$this->load->view('data_view', $data);
}
And reference it like $user_info in your view.
You are not passing the array correctly to view . Pass your data like this
public function index(){
$this->load->model('mymodel');
$user_info['user_info'] = $this->mymodel->get_data();
$this->load->view('inc/header_view');
$this->load->view('data_view', $user_info);
}

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

insert data into database with codeigniter

Trying to insert a row into my database with CodeIgniter.
My database table is Customer_Orders and the fields are CustomerName and OrderLines. The variables are being submitted correctly.
My Controller is( sales.php ):
function new_blank_order_summary()
{
$data = array(
'OrderLines'=>$this->input->post('orderlines'),
'CustomerName'=>$this->input->post('customer')
);
$this->sales_model->order_summary_insert($data);
$this->load->view('sales/new_blank_order_summary');
}
My Model is( sales_model.php ):
function order_summary_insert($data){
$this->db->insert('Customer_Orders',$data);
}
Whilst the view loads correctly, no data is inserted into the database.
Any ideas as to why not?
Try this in your model:
function order_summary_insert()
$OrderLines=$this->input->post('orderlines');
$CustomerName=$this->input->post('customer');
$data = array(
'OrderLines'=>$OrderLines,
'CustomerName'=>$CustomerName
);
$this->db->insert('Customer_Orders',$data);
}
Try to use controller just to control the view and models always post your values in model. it makes easy to understand.
Your controller will be:
function new_blank_order_summary() {
$this->sales_model->order_summary_insert($data);
$this->load->view('sales/new_blank_order_summary');
}
It will be better for you to write your code like this.
In your Controller Write this code.
function new_blank_order_summary() {
$query = $this->sales_model->order_summary_insert();
if($query) {
$this->load->view('sales/new_blank_order_summary');
} else {
$this->load->view('sales/data_insertion_failed');
}
}
and in your Model
function order_summary_insert() {
$orderLines = trim(xss_clean($this->input->post('orderlines')));
$customerName = trim(xss_clean($this->input->post('customer')));
$data = array(
'OrderLines'=>$orderLines,
'CustomerName'=>$customerName
);
$this->db->insert('Customer_Orders',$data);
return ($this->db->affected_rows() != 1) ? false : true;
}
function saveProfile(){
$firstname = $this->input->post('firstname');
$lastname = $this->input->post('lastname');
$post_data = array('firstname'=> $firstname,'lastname'=>$lastname);
$this->db->insert('posts',$post_data);
return $this->db->insert_id();
}
View
<input type="text" name="name"/>
<input type="text" name="class"/>
Controller
function __construct()
{
parent:: __construct();
$this->load->Model('Model');
}
function index()
{
$this->load->view('view');
}
function user(){
if (isset($_POST['submit'])){
$data = array('name'=>$_POST['name'],
'class'=>$_POST['class']);
$this->Model->insert($data);
}
}
Model
function insert($data)
{
$this->db->insert('table_name',$data);
return true;
}
Based on what I see here, you have used lowercase fieldnames in your $data array, and uppercase fieldnames in your database table.
function order_summary_insert()
$OrderLines=$this->input->post('orderlines');
$CustomerName=$this->input->post('customer');
$data = array(
'OrderLines'=>$OrderLines,
'CustomerName'=>$CustomerName
);
$this->db->insert('Customer_Orders',$data);
}
Check your controller:
function order()
$OrderLines = $this->input->post('orderlines');
$CustomerName = $this->input->post('customer');
$data = array(
'OrderLines' => $OrderLines,
'CustomerName' =>$CustomerName
);
$this->db->insert('Customer_Orders', $data);
}
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Cnt extends CI_Controller {
public function insert_view()
{
$this->load->view('insert');
}
public function insert_data(){
$name=$this->input->post('emp_name');
$salary=$this->input->post('emp_salary');
$arr=array(
'emp_name'=>$name,
'emp_salary'=>$salary
);
$resp=$this->Model->insert_data('emp1',$arr);
echo "<script>alert('$resp')</script>";
$this->insert_view();
}
}
for more detail visit:
http://wheretodownloadcodeigniter.blogspot.com/2018/04/insert-using-codeigniter.html
Just insert $this->load->database(); in your model:
function order_summary_insert($data){
$this->load->database();
$this->db->insert('Customer_Orders',$data);
}

Categories