codeigniter help causing error while loading model - codeigniter

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 :)

Related

Codeigniter global variable in view

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

How to get all data from Category in Codeigniter

I am new in Codeigniter, Please help me.
My Codeigniter url is - http://localhost/framework/CodeIgniter/index.php/restaurant/patna/
I want to get all data.
I set the route -
$route['restaurant(:any)'] = "Restaurant/getRestaurantByCity/$1";
And my function in Controller is
here i want the category id where pass the cat_id in below function for get all the data of that category
public function getRestaurantByCity()
{
$rst_list = $this->Restaurant_model->get_restaurant_by_city();
}
try this
controller
$this->data['RestaurantByCity'] = $this->Restaurant_model->getRestaurantByCity();
echo "<pre>"; print_R($this->data['RestaurantByCity']);
model
public function getRestaurantByCity($ids){
$sql ="select * from categoriestableName where categories_id in($ids) order by categories_id asc";
$rs = $this->db->query($sql);
foreach($rs->result() as $record ){
$result[] = $record;
}
return $result;
}
This should work
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Restaurant extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function getRestaurantByCity($id)
{
$this->load->model('Restaurant_model');
$rst_list = $this->Restaurant_model->get_restaurant_by_city($id);
}
}

CodeIgniter Call to a member function on a non-object in [library]

I'am trying call custom library function witch should return inputed values back to form, but I'am geting error.
enter image description here
Controler:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Guest extends CI_Controller {
public function __construct(){
parent::__construct();
error_reporting(E_ALL ^ (E_NOTICE));
$this->load->helper(array('form', 'url', 'date'));
$this->load->library('form_validation', 'uri');
$this->load->model('dayData');
$this->load->library('session');
$this->load->library('guest');
}
public function index(){
$this->login();
}
public function dataToView($data, $viewFile){
$this->load->view('template/header');
if($viewFile != ''){
$this->load->view('user/' . $viewFile, $data);
}
$this->load->view('template/footer');
}
public function login(){
$this->dataToView($data, 'guest/login');
}
public function registration(){
if($this->input->post('registrationSubmit') !== null) {
//$this->form_validation->set_error_delimiters('<div class="alert alert-warning" role="alert">', '</div>');
$this->config->load('form_validation');
$this->form_validation->set_rules($this->config->item('registrationValidation'));
if($this->form_validation->run() == FALSE){
var_dump($this->guest->registrationPost());
$this->dataToView($data, 'guest/registration');
} else {
echo "string";
}
} else {
$this->dataToView($data, 'guest/registration');
}
}
}
Library:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Guest {
protected $CI;
public function __construct(){
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
//$this->CI->load->model('Guest');
$this->CI->lang->load('error', 'english');
}
public function registrationPost(){
$result = array('name' => $this->CI->input->post('name'),
'nickName' => $this->CI->input->post('nickName'),
'email' => $this->CI->input->post('email'));
return $result;
}
}
There is a naming conflict between the controller and the custom class. They should not have the same name.
You have duplicate class names. The controller class name is Guest and the library class name is also Guest.
When CodeIgniter goes to load the Guest library, it will skip over it and log a debug message. https://github.com/bcit-ci/CodeIgniter/blob/develop/system/core/Loader.php#L1032
I suggest renaming your library to something else, Registration perhaps?

How to pass variables in codeigniter 2

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

Passing query result to 2nd function in Codeigniter

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

Resources