I have following
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Hello extends CI_Controller {
var $name = 'test';
function index() {
$this->name = 'Andy';
$data['name'] = $this->name;
$this->load->view('you_view', $data); // THIS WORKS
}
function you() {
$data['name'] = $this->name;
$this->load->view('you_view', $data); // BUT THIS DOESN'T WORK
}
}
My question is how to I pass the $this->name = 'Andy'; to you() ??
Since it is being set in a different method of the controller, which equates to another request in your code, you will need to store it in a session variable to have it persist across page requests.
function index() {
$this->name = 'Andy';
$data['name'] = $this->name;
$this->session->set_userdata('name', $this->name);
$this->load->view('you_view', $data); // THIS WORKS
}
function you() {
$data['name'] = $this->session->userdata('name');
$this->load->view('you_view', $data); // BUT THIS DOESN'T WORK
}
If its a value that is part of the class you can put it in the constructor
class Hello extends CI_Controller {
public function __construct() {
parent::__construct();
// will be available to any method in the class
$this->name = 'andy';
}
Related
I don't know if the title above is an correct title about my question.
Is there a way to declare a variable which we can access it from anywhere in view without need to redefine it again in each function in controller?
for example in controller file Students.php contains many function that handle the views, take a look below :
public function __construct() {
parent::__construct();
$data['count_student'] = $this->m_data->allStudent(); // count all students
}
public function index() {
$data['content'] = 'view-students';
$this->load->view('frontend/header' , $data);
}
public function showDetails() {
$data['content'] = 'view-detail-students';
$this->load->view('frontend/header' , $data);
}
I expected we can access $count_student in both view-students.php and view-detail-student.php without to define $data['count_student'] = $this->m_data->allStudent(); on each function that handle the view.
Is there possible ways to do that?
In the application/core/ create MY_Controller.php
<?php
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('m_data');
$this->data['count_student'] = $this->m_data->allStudent();
}
}
Controller use $this->data
class Students extends MY_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->data['content'] = 'view-students';
$this->load->view('frontend/header', $this->data);
}
public function showDetails() {
$this->data['content'] = 'view-detail-students';
$this->load->view('frontend/header', $this->data);
}
}
Now that you have extended the controller you shoudld be able to just go like
<?php echo $count_student;?>
On the view
I noticed that you can access variables in views without passing them if you declare them in the controller with $this->. Probably because they default to public visibility.
public function __construct() {
parent::__construct();
// $data['count_student'] = $this->m_data->allStudent(); // count all students
//
$this->count_all_the_students = $this->m_data->allStudents();
}
public function index() {
$data['content'] = 'view-students';
$this->load->view('frontend/header' , $data);
}
And then in the view you can use $this->count_all_the_students without putting it in the $data array.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php
echo 'I have misled ' . $this->count_all_the_students . ' students with my MVC breaking suggestions.';
If you are using the same variable in every controller function then you have to declare it as follows
class Example extends CI_Controller{
protected $data = array();
public function __construct() {
parent::__construct();
$this->data['count_student'] = $this->m_data->allStudent();
}
public function index() {
$this->data['content'] = 'view-students'; //variables are same
$this->load->view('frontend/header' , $this->data);
}
public function showDetails() {
$this->data['content'] = 'view-detail-students'; //variables are same
$this->load->view('frontend/header' , $this->data);
}
}
This applies only if you have common variables for all views in this controller.
If you are using different variables then use the following code.
class Example extends CI_Controller{
protected $count_student= "";
public function __construct() {
parent::__construct();
$this->count_student = $this->m_data->allStudent();
}
public function index() {
$data['content'] = 'view-students'; //Variable is different
$data['count_student'] = $this->count_students;
$this->load->view('frontend/header' , $data);
}
public function showDetails() {
$data['details'] = 'view-detail-students'; // Variable is different
$data['count_student'] = $this->count_students;
$this->load->view('frontend/header' , $data);
}
}
I have a model called register_model.php, which I have loaded in a function in my controller (register_controller.php). Model file is placed into model folder itself. Still, I get this error.
An Error Was Encountered
Unable to locate the model you have specified: register_model
register_controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Register_controller extends CI_Controller
{
function __construct()
{
parent::__construct();
}
// function index()
// {
//
// }
public function register() {
if ($this->session->userdata('logged_in'))
{
//user is already logged in
redirect('index.php');
}
else {
//init
//$data['country_list']=$this->config->item('um_country_list');
$data['username'] = '';
$data['firstname'] = '';
$data['lastname'] = '';
$data['email'] = '';
// $data['password'] = '';
//$data['userlevel'] = '';
//load rules
$rules = $this->config->item('um_register_rules');
//default msg
$data['msg'] = $this->lang->line('um_form_msg');
$this->load->model('register_model');
if (isset($_POST['submit'])) {
//the user has submitted the form
//get the user input
$data['username'] = $this->input->post('username');
$data['firstname'] = $this->input->post('firstname');
$data['lastname'] = $this->input->post('lastname');
$data['email'] = $this->input->post('email');
$data['password'] = $this->input->post('password');
//$data['userlevel'] = $this->input->post('userlevel');
$this->form_validation->set_rules($rules); //check with the rules
if ($this->form_validation->run() === FALSE) {
//validation failed
$data['msg'] = $this->lang->line('um_form_error');
$this->load->view('user_register_form', $data);
} else {
//validation passed
$dbdata = array(
'username' => $this->input->post('username'),
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
//'userlevel' => $this->input->post('userlevel')
);
$this->register_model->register_user($dbdata);
$data['msg']=$this->lang->line('um_form_activate');
//render the view
$this->load->view('um_msg', $data);
}
} else {
//render the view
$this->load->view('user_register_form', $data);
}
}
}
}
?>
register_model.php
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Register_model extends CI_Model {
function __construct() {
parent::__construct();
}
public function register_user($dbdata) {
$this->db->insert('users', $dbdata);
}
}
?>
Probably you should include your model inside your controller, try to include after parent::__construct
This should look like so:
class Registration extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('register_model');
}
or if you using this model in most controllers you can include it using autoload, go to /config/autoload.php search for $autoload['model'] and add your model inside the suitable array
First of all load your model in your controller ..
function __construct() {
parent::__construct();
$this->load->model('register_model');
}
This will work for you...
I'm a newbe in codeigniter.
something is going wrong with I think the model.
this is the controler:
<?php
class Fuel extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('html');
$this->load->library('table');
}
public function image() {
$data['title'] = 'test';
$data['main_content'] = 'imagetest';
$this->load->view("template", $data);
}
public function overview() {
$this->load->model('Get_DB');
$this->Get_DB->overview() ;
$data['title'] = 'overview';
$data['main_content'] = 'overview';
$this->load->view("template", $data);
}
when I load the image function, it works just fine, but the function overview is the problem.
this is my model:
<?php
class Get_DB extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
public function overzicht() {
$query = $this->db->query("SELECT * FROM invoer "
. "ORDER BY datum DESC");
$gen_query = $this->table->generate($query);
return $gen_query;
}
}
and this is my view:
<?php
echo $gen_query;
and if you want to know: my template is this:
<?php
$this->load->view('templates/header');
$this->load->view($main_content);
$this->load->view('templates/footer');
now when I open my view I get this message:
A PHP Error was encountered
Severity: Notice Message: Undefined variable: gen_query Filename:
views/overzicht.php Line Number: 3
in the model you see that I have made a var $gen_query
so why is that undifined?
regards,
Ralph
Try:
public function overview() {
$this->load->model('Get_DB');
$data = array();
$data['gen_query'] = $this->Get_DB->overzicht() ; #corrected model function and save the result in `gen_query`
$data['title'] = 'overview';
$data['main_content'] = 'overview';
$this->load->view("template", $data);
}
In Controler:
public function overview() {
$this->load->model('Get_DB');
$result = $this->Get_DB->overview() ;
$data['title'] = 'overview';
$data['main_content'] = 'overview';
$data['re'] = $result;
$this->load->view("template", $data);
}
And In view page you can retrive the result
like
foreach($re->result() as $row)
{
//You can get each row data here $row->your_field_names
}
I am not sure whats wrong with my code.......it causing an error while loading model.......
please help...........
my controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Exams extends CI_Controller {
public function index(){
$ob = new exam_class();
$ob->set_exam(0,'Html exam','1','20');
$ob->create_exam();
echo 'success';
}
}
class exam_class{
private $id;
private $title;
private $catagory;
private $timeLength;
function set_exam($id,$title,$catagory,$timeLength){
$this->id = $id;
$this->title = $title;
$this->catagory = $catagory;
$this->timeLength = $timeLength;
}
function create_exam(){
$this->load->model('examModel');
$this->examModel->create_exams($title,$catagory,$timeLength);
}
}
model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class ExamModel extends CI_Model {
public function create_exams($title,$catagory,$timeLength){
$data = array(
'title' => $title ,
'catagory' => $catagory ,
'timeLength' => $timeLength
);
$this->db->insert('exams', $data);
}
}
error
A PHP Error was encountered
Severity: Notice
Message: Undefined property: exam_class::$load
Filename: controllers/exams.php
Line Number: 26
Fatal error: Call to a member function model() on a non-object in C:\xampp\htdocs\exam\application\controllers\exams.php on line 26
You shouldn't put more than one class in a file. Controller should be something like this.
class Exams extends CI_Controller {
private $id;
private $title;
private $catagory;
private $timeLength;
public function __construct()
{
parent::__construct();
$this->load->model('examModel');
}
public function index(){
$this->set_exam(0,'Html exam','1','20');
$this->create_exam();
echo 'success';
}
function set_exam($id,$title,$catagory,$timeLength){
$this->id = $id;
$this->title = $title;
$this->catagory = $catagory;
$this->timeLength = $timeLength;
}
function create_exam(){
$this->examModel->create_exams($title,$catagory,$timeLength);
}
}
Along with #shin i want to include that go to this file
....\testproject\application\config\autoload.php
and edit this to add your models
$autoload['model'] = array('modelName1','modelName2');
and to load the models from any time from any controller . This will automatically load your models.No need to add
$this->load->model('modelName');
Tip : Keep it simple
In your controller :
public function __construct()
{
parent::__construct();
$this->load->model('examModel');
}
public function index()
{
$exam_data = $this->process_exam_data(0,'Html exam','1','20');
$insert_status = $this->examModel->create_exams($exam_data);
if($insert_status===TRUE){
echo "Exam Insert Successful!";
}
else{
echo "Exam Insert Failed";
}
}
public function process_exam_data($id, $title, $category, $timelength)
{
// Do whatever you want with the data, calculations etc.
// Prepare your data array same as to be inserted into db
$final_data = array(
'title' => $processed_title,
'catagory' => $processed_category,
'timeLength' => $processed_time
);
return $final_data;
}
And in your model :
public function create_exams($data)
{
$result = $this->db->insert('exams', $data); // Query builder functions return true on success and false on failure
return $result;
}
Your index function is the main function which does the calling, whereas all the processing work is done in the process_exam_data function.
Have a nice day :)
I'm trying to run two queries in two functions in a model on Codeigniter. The 2nd query runs based on the result of the first by passing the variable between the functions.
The first query gets the row from the 'photos' database based on the URL the user goes to. The second query is run against the 'users' database and the row is selected based on the 'userid' field from the row of the first query.
I need to be able to get all data from the rows of both queries. I get a 404 error at the moment, any ideas as how to get it working?
Code is as follows:
Model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Viewphoto_model extends CI_Model {
public function get_photo($id)
{
$db_photos = $this->load->database('photos', TRUE);
$db_photos->select('*');
$db_photos->select("DATE_FORMAT(uploaddate, '%d/%m/%y') as uploaddate_formatted", FALSE);
$db_photos->from('photos');
$db_photos->where('approved', '1');
$db_photos->where('id', $id);
$result = $db_photos->get()->row();
$userid = $this->get_user($result->userid);
}
public function get_user($userid)
{
$db_users = $this->load->database('users', TRUE);
$db_users->select('firstname, lastname, email');
$db_users->from('useraccounts');
$db_users->where('id', $userid);
$query = $db_users->get();
return $query->row();
}
}
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Viewphoto extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('viewphoto_model');
}
public function view($id)
{
$data['photo'] = $this->viewphoto_model->get_photo($id);
if (empty($data['photo']))
{
show_404();
}
$data['user'] = $this->viewphoto_model->get_user($userid);
if (empty($data['user']))
{
show_404();
}
$data['title'] = $data['photo']->title.' by '.$data['photo']->username;
$data['meta_description'] = $data['photo']->description;
$data['directory'] = 'sub';
$this->load->view('templates/header', $data);
$this->load->view('viewphoto/viewphoto', $data);
$this->load->view('templates/footer', $data);
}
}
You seem to have a slight logic issue. Your get_photo() function should return the photo object, which your controller can then use in the call to get_user()...
public function get_photo($id)
{
$db_photos = $this->load->database('photos', TRUE);
$db_photos->select('*');
$db_photos->select("DATE_FORMAT(uploaddate, '%d/%m/%y') as uploaddate_formatted", FALSE);
$db_photos->from('photos');
$db_photos->where('approved', '1');
$db_photos->where('id', $id);
return $db_photos->get()->row();
}
Then in your controller....
public function view($id)
{
$data['photo'] = $this->viewphoto_model->get_photo($id);
if (empty($data['photo']))
{
show_404();
}
// Pass the photo's userid here
$data['user'] = $this->viewphoto_model->get_user($data['photo']->userid);
if (empty($data['user']))
{
show_404();
}
// ...
}