PHP MVC can't access controller - php

I have this simple PHP code where I have created a new model with a celebrity name, a controller that accesses the celebrity name from the model, and a view to display the name. For some reason using the path below I can't display the name accessing the controller. I can't find out what I am missing or doing wrong.
Thanks for the help!
http://localhost/ci/Starcontroller/guess
Controller->
<?php
class Starcontroller extends CI_Controller{
function __construct() {parent::__construct();}
function guess()
{
$this->load->model('starmodel');
$newstarr = $this->starmodel->lookup();
$this->load->view('starview',$newstarr);
}
}
?>
Model->
<?php
class starmodel extends CI_Model{
function __construct()
{
parent::__construct();
}
public function lookup(){
$celebrity = "Anna";
return $celebrity;
}
}
?>
View ->
<html>
<head></head>
<body>
<?php
echo $newstarr;
?>
</body>
</html>

First initial alphabet of Class name and File name of controller and model are in capital letter's check your model class name
Then in controller change to this
<?php
class Starcontroller extends CI_Controller {
function __construct() {
parent::__construct();
// Would load model in here and other helpers and libraries.
// So can access through all functions on controller.
// $this->load->model('starmodel');
}
function guess() {
$this->load->model('starmodel');
$newstarr['data'] = $this->starmodel->lookup();
$this->load->view('starview',$newstarr);
}
}
In view
<?php echo $data ?>

From controller, you would like to pass an associative array of data to the view.
So change this part:
$newstarr = $this->starmodel->lookup();
$this->load->view('starview',$newstarr);
To this:
$data['newstarr'] = $this->starmodel->lookup();
$this->load->view('starview',$data);
Rest of your code may stay the same.

Related

How can I access a variable value in view from controller

I've got two controller-view pair. I load a view, from my A_Controller, with $data variable. In the new view(B_View) with a new controller(B_Controller) I can access that data, but I would like to use it in the view's controller (B_Controller) too. Is there anyway to access itt?
A_Controller
class A_Controller extends CI_Controller {
public function index{
$variable= "some_data";
$data['variable'] = $variable
$this->load->view('B_View', $data)
}
}
B_View
<html>
<body>
<!-- I can access it here -->
<h1><?php echo $variable;?><h1>
</body>
</html>
B_Controller
class B_Controller extends CI_Controller {
public function some_function{
$new_variable = $variable; //but I can't access it here :(
}
}
Use SESSIONS
Enable sessions globally in config/autoload.php
$autoload['libraries'] = array('session');
In A_Controller, initialise your variable and store it in a session
class A_Controller extends CI_Controller {
public function index{
$variable= "some_data";
$this->session->set_userdata(array('variable'=>$variable)); //store variable in a session
$data['variable'] = $variable;
$this->load->view('B_View', $data)
}
}
In B_Controller, get the variable via the session
class B_Controller extends CI_Controller {
public function some_function{
$new_variable = $this->session->userdata('variable'); //get back variable from session
}
}
Hope it helps :)
If you are trying to pass sensitive data like mobile number or something personal I don't accept using session to pass data across controller functions. If you have lot of variables and if they fetch data from a db it better to make a separate controller to load required data into a function. But keep in mind dont load any view in this function. Just load required data. If your data fetching function has lot of variables it may affect to your web site loading speed. However when you have a seperate function and a controller to load data then you can redirect to that controller in other functions and then access into the required variable.
class B_Controller extends CI_Controller {
public function some_function{
redirect('/Data_Controller/data_function');
$new_variable = $variable;
}
}
Hope this make sense to you problem. Thanks
You can use codeigniter Session to pass data from one controller to another controller or redirect the controller with controller name and the method
class B_Controller extends CI_Controller {
public function some_function{
redirect('/A_Controller/index');
$new_variable = $variable;
}
}
Via session
First set the $variable into flash data
class A_Controller extends CI_Controller {
public function index{
$this->load->library('session');
$variable= "some_data";
$data['variable'] = $variable;
$this->session->set_flashdata('variableName', $variable);
$this->load->view('B_View', $data)
}
}
Now fecth it in second controller
class B_Controller extends CI_Controller {
public function some_function{
$new_variable = $this->session->flashdata('variableName');
$new_variable = $variable;
}
}
Please note I have not tested this code but I think you may able to grab something via this.Thanks
Why dont you do $data['variable'] = "SOME DATA" in the controller you will be able to use it in the view like <?= $variable; ?> :)

Calling a Controller Method in a View - Codeigniter [duplicate]

How to call codeigniter controller function from view? When i call the function in a controller, get a 404 page.
You can call controller function from view in the following way:
Controller:
public function read() {
$object['controller'] = $this;
$this->load->view('read', $object);
}
View:
// to call controller function from view, do
$controller->myOtherFunct();
Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.
A good start for clarifying the best practice is to follow this tutorial:
https://codeigniter.com/user_guide/tutorial/index.html
It's simple, but it really lays out an excellent how-to.
I hope this helps!
You can call a controller function with AJAX on your view.
In this case, I'm using the jQuery library to make the call.
<script type="text/javascript">
$.ajax({
url: "<?=site_url("controller/function")?>",
type: "post", // To protect sensitive data
data: {
ajax:true,
variableX: "string",
variableY: 25
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
}
});
</script>
This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.
I would like to answer this question as this comes all times up in searches --
You can call a controller method in view, but please note that this is not a good practice in any MVC including codeigniter.
Your controller may be like below class --
<?php
class VCI_Controller extends CI_Controller {
....
....
function abc($id){
return $id ;
}
}
?>
Now You can call this function in view files as below --
<?php
$CI =& get_instance();
$CI->abc($id) ;
?>
class MY_Controller extends CI_Controller {
public $CI = NULL;
public function __construct() {
parent::__construct();
$this->CI = & get_instance();
}
public function yourMethod() {
}
}
// in view just call
$this->CI->yourMethod();
Try this one.
Add this code in Your View file
$CI = & get_instance();
$result = $CI->FindFurnishName($pera);
Add code in Your controller File
public function FindFurnishName($furnish_filter)
{
$FindFurnishName = $this->index_modal->FindFurnishName($furnish_filter);
$FindFurnishName_val = '';
foreach($FindFurnishName as $AllRea)
{
$FindFurnishName_val .= ",".$AllRea->name;
}
return ltrim($FindFurnishName_val,',');
}
where
FindFurnishName is name of function which is define in Your Controller.
$pera is a option ( as your need).
One idea i can give is,
Call that function in controller itself and return value to view file. Like,
class Business extends CI_Controller {
public function index() {
$data['css'] = 'profile';
$data['cur_url'] = $this->getCurrURL(); // the function called and store val
$this->load->view("home_view",$data);
}
function getCurrURL() {
$currURL='http://'.$_SERVER['HTTP_HOST'].'/'.ltrim($_SERVER['REQUEST_URI'],'/').'';
return $currURL;
}
}
in view(home_view.php) use that variable. Like,
echo $cur_url;
views cannot call controller functions.
I know this is bad..
But I have been in hard situation where it is impossible to put this back to controller or model.
My solution is to call a function on model.
It can be do inside a view.
But you have to make sure the model has been loaded to your controller first.
Say your model main_model, you can call function on the model like this on your view :
$this->main_model->your_function();
Hope this help. :)
We can also pass controller function as variable in the view page.
class My_controller extends CI_Controller {
public function index() {
$data['val']=3;
$data['square']=function($val){
return $val*$val;
};
$this->load->view('my-view',$data);
}
}
In the view page
<p>Square of <?=$val?>
<?php
echo $square($val);
?>
</p>
The output is 9
it is quite simple just have the function correctly written in the controller class and use a tag to specify the controller class and method name, or any other neccessary parameter..
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Iris extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('script');
$this->load->model('alert');
}public function pledge_ph(){
$this->script->phpledge();
}
}
?>
This is the controller class Iris.php
and the model class with the function pointed to from the controller class.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Script extends CI_Model {
public function __construct() {
parent::__construct();
// Your own constructor code
}public function ghpledge(){
$gh_id = uniqid(rand(1,11));
$date=date("y-m-d");
$gh_member = $_SESSION['member_id'];
$amount= 10000;
$data = array(
'gh_id'=> $gh_id,
'gh_member'=> $gh_member,
'amount'=> $amount,
'date'=> $date
);
$this->db->insert('iris_gh',$data);
}
}
?>
On the view instead of a button just use the anchor link with the controller name and method name.
<html>
<head></head>
<body>
PLEDGE PH
</body>
</html>
I had this same issue , but after a couple of research I fond it out it's quite simple to do,
Locate this URL in your Codeigniter project: application/helpers/util_helper.php
add this below code
//you can define any kind of function but I have queried database in my case
//check if the function exist
if (!function_exists('yourfunctionname')) {
function yourfunctionname($param (if neccesary)) {
//get the instance
$ci = & get_instance();
// write your query with the instance class
$data = $ci->db->select('*');
$data = $ci->db->from('table');
$data = $ci->db->where('something', 'something');
//you can return anythting
$data = $ci->db->get()->num_rows();
if ($data > 0) {
return $data;
} else {
return 0;
}
}
}
I know this question is old but it is still a relevant question. From my experience there are situations that warrant calling a function from view in your Codeigniter 4 app, I'll just advise that you keep it clean and minimal. Below is how I have called controller function from view:
In your controller file add this code
public function index()
{
$data = [];
$model = new UsersModel();
$data['users'] = $model->findAll();
// $this refers to the controller to be called from view
$data['callfromview'] = $this;
return view('users', $data)
}
In your view, call the controller like this:
<?php $something = $callfromview->fetch_data($id);?>
Finally in the controller, create the fetch_data function
public function fetch_data($id)
{
$image = new ImageModel();
return $image->find($id);
}
the END!
if you need to call a controller from a view,
maybe to load a partial view,
you thinking as modular programming,
and you should implement HMVC structure in lieu of plane MVC.
CodeIgniter didnt implement HMVC natively,
but you can use this useful library in order to implement HMVC.
https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc
after setup
remember:that all your controllers should extends from MX_Controller in order to using this feature.
Go to the top of your View code and do it like this :
<?php
$this->load->model('MyModelName');
$MyFunctionReturnValue = $this->MyModelName->MyFunctionName($param));
?>
<div class="row">
Your HTML CODE
</div>

CodeIgniter don't show anything

I now trying CodeIgniter for the first time. I created a new route rule in the routes.php
$route['ajax/rendeles/(:any)']='ajax/rendeles/$1';
$route['ajax']="ajax";
And a controller (ajax.php):
<?php
class ajax extends CI_Controller{
public function rendeles($id){
$this->load->view("ajax/rendeles/".$id, $);
echo $id;
}
}
?>
A view (rendeles_view.php):
<?php
$this->load->model("ajax/rendeles_model");
$result=$this->rendeles_model->rendelesReszletei($id);
foreach ($result as $row){
echo $row->product."<br>";
}?>
And a model (rendeles_model.php):
<?php
class rendeles_model extends CI_Model{
public function rendelesReszletei($id){
$query=$this->db->get_where("_order_items", array("id_order"=>$id));
return $query->result();
}
}?>
But when I enter into the browser the domainname/ajax/rendeles/4072 (<-this is an id of an order), but It don't show anything.
Somebody can help me?
Thanks in advance, kukko.
<?php
class ajax extends CI_Controller{
public function rendeles($id){
$data['id'] = $id;
$this->load->view("ajax/rendeles", $data);
echo $id;
}
}
?>
Your class names must start with an uppercase letter, like this:
class Ajax extends CI_Controller{
// ...
class Rendeles_model extends CI_Model{
// ...

How to set the controller and model in layout/default to load in all pages

Layout
For all pages when I load the data works but the model and controller do not work. Other model which I have assigned works. I mean, one controller and model of layout for all pages but other page their own model and controller. One controller for all pages and one for each page.
<?php foreach ($sidebars as $row): ?>
<tr><td><?php echo $row->title; ?> </td></tr>
<?php endforeach; ?>
<div id="main" role="main" class="content">
{content}------here this show my pages content other model and controller
</div>
Controller
on my controller i load my page
now if i load other page again i have to enter the
$this->load->model('side_model');
$data['sidebars'] = $this->side_model->get_sidebar();
this one of my page controller it works but other controller if don't mention about so not works i want to make it as controller for every page and i don't want to mention in each page controller above code
"<?php"
public $layout = 'default'
public function index()
{
$this->load->model('side_model');
$data['sidebars'] = $this->side_model->get_sidebar();
$this->load->view('Layout/default',$data);
}
Model
function get_sidebar(){
$this->db->select('*');
$this->db->from('side');
$this->db->where('active','1');
$this->db->order_by('added_date', 'DESC');
return $this->db->get()->result();
How do I make one main controller and model with many function for all pages?
Create a file called core/MY_Controller.php:
class MY_Controller extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model("side_model");
$this->data["sidebars"] = $this->side_model->get_sidebar();
}
protected function get_html_meta($meta){
// method will be available for all extending controllers
return ucfirst($meta)." ".date("Y-m-d");
}
}
From now on you should extend MY_Controller and not CI_Controller, in your existing controller you can now pass the varible $this->data which is available to the view (i have added a few examples of $this->data usage and its scope:
class your_controller extends MY_Controller {
public function index(){
$this->data["html_meta"] = $this->get_html_meta("this is meta");
$this->data["html_title"] = "Hello World!";
$this->load->view('Layout/default',$this->data);
}
}
NOTE: unlike $this->data, the scope for $data is inside the function you declare it only.
As for a global model, once the MY_Controller constructor (or autoload.php) loads the model you can invoke the model as long as you other controllers extend MY_Controller.
Write you own controller
class ParentController extends CI_Controller {
public function index()
{
echo 'Hello World!';
}
}
class Blog extends ParentController {
public function index()
{
echo 'Hello World!';
}
}

How to call codeigniter controller function from view

How to call codeigniter controller function from view? When i call the function in a controller, get a 404 page.
You can call controller function from view in the following way:
Controller:
public function read() {
$object['controller'] = $this;
$this->load->view('read', $object);
}
View:
// to call controller function from view, do
$controller->myOtherFunct();
Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.
A good start for clarifying the best practice is to follow this tutorial:
https://codeigniter.com/user_guide/tutorial/index.html
It's simple, but it really lays out an excellent how-to.
I hope this helps!
You can call a controller function with AJAX on your view.
In this case, I'm using the jQuery library to make the call.
<script type="text/javascript">
$.ajax({
url: "<?=site_url("controller/function")?>",
type: "post", // To protect sensitive data
data: {
ajax:true,
variableX: "string",
variableY: 25
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
}
});
</script>
This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.
I would like to answer this question as this comes all times up in searches --
You can call a controller method in view, but please note that this is not a good practice in any MVC including codeigniter.
Your controller may be like below class --
<?php
class VCI_Controller extends CI_Controller {
....
....
function abc($id){
return $id ;
}
}
?>
Now You can call this function in view files as below --
<?php
$CI =& get_instance();
$CI->abc($id) ;
?>
class MY_Controller extends CI_Controller {
public $CI = NULL;
public function __construct() {
parent::__construct();
$this->CI = & get_instance();
}
public function yourMethod() {
}
}
// in view just call
$this->CI->yourMethod();
Try this one.
Add this code in Your View file
$CI = & get_instance();
$result = $CI->FindFurnishName($pera);
Add code in Your controller File
public function FindFurnishName($furnish_filter)
{
$FindFurnishName = $this->index_modal->FindFurnishName($furnish_filter);
$FindFurnishName_val = '';
foreach($FindFurnishName as $AllRea)
{
$FindFurnishName_val .= ",".$AllRea->name;
}
return ltrim($FindFurnishName_val,',');
}
where
FindFurnishName is name of function which is define in Your Controller.
$pera is a option ( as your need).
One idea i can give is,
Call that function in controller itself and return value to view file. Like,
class Business extends CI_Controller {
public function index() {
$data['css'] = 'profile';
$data['cur_url'] = $this->getCurrURL(); // the function called and store val
$this->load->view("home_view",$data);
}
function getCurrURL() {
$currURL='http://'.$_SERVER['HTTP_HOST'].'/'.ltrim($_SERVER['REQUEST_URI'],'/').'';
return $currURL;
}
}
in view(home_view.php) use that variable. Like,
echo $cur_url;
views cannot call controller functions.
I know this is bad..
But I have been in hard situation where it is impossible to put this back to controller or model.
My solution is to call a function on model.
It can be do inside a view.
But you have to make sure the model has been loaded to your controller first.
Say your model main_model, you can call function on the model like this on your view :
$this->main_model->your_function();
Hope this help. :)
We can also pass controller function as variable in the view page.
class My_controller extends CI_Controller {
public function index() {
$data['val']=3;
$data['square']=function($val){
return $val*$val;
};
$this->load->view('my-view',$data);
}
}
In the view page
<p>Square of <?=$val?>
<?php
echo $square($val);
?>
</p>
The output is 9
it is quite simple just have the function correctly written in the controller class and use a tag to specify the controller class and method name, or any other neccessary parameter..
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Iris extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('script');
$this->load->model('alert');
}public function pledge_ph(){
$this->script->phpledge();
}
}
?>
This is the controller class Iris.php
and the model class with the function pointed to from the controller class.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Script extends CI_Model {
public function __construct() {
parent::__construct();
// Your own constructor code
}public function ghpledge(){
$gh_id = uniqid(rand(1,11));
$date=date("y-m-d");
$gh_member = $_SESSION['member_id'];
$amount= 10000;
$data = array(
'gh_id'=> $gh_id,
'gh_member'=> $gh_member,
'amount'=> $amount,
'date'=> $date
);
$this->db->insert('iris_gh',$data);
}
}
?>
On the view instead of a button just use the anchor link with the controller name and method name.
<html>
<head></head>
<body>
PLEDGE PH
</body>
</html>
I had this same issue , but after a couple of research I fond it out it's quite simple to do,
Locate this URL in your Codeigniter project: application/helpers/util_helper.php
add this below code
//you can define any kind of function but I have queried database in my case
//check if the function exist
if (!function_exists('yourfunctionname')) {
function yourfunctionname($param (if neccesary)) {
//get the instance
$ci = & get_instance();
// write your query with the instance class
$data = $ci->db->select('*');
$data = $ci->db->from('table');
$data = $ci->db->where('something', 'something');
//you can return anythting
$data = $ci->db->get()->num_rows();
if ($data > 0) {
return $data;
} else {
return 0;
}
}
}
I know this question is old but it is still a relevant question. From my experience there are situations that warrant calling a function from view in your Codeigniter 4 app, I'll just advise that you keep it clean and minimal. Below is how I have called controller function from view:
In your controller file add this code
public function index()
{
$data = [];
$model = new UsersModel();
$data['users'] = $model->findAll();
// $this refers to the controller to be called from view
$data['callfromview'] = $this;
return view('users', $data)
}
In your view, call the controller like this:
<?php $something = $callfromview->fetch_data($id);?>
Finally in the controller, create the fetch_data function
public function fetch_data($id)
{
$image = new ImageModel();
return $image->find($id);
}
the END!
if you need to call a controller from a view,
maybe to load a partial view,
you thinking as modular programming,
and you should implement HMVC structure in lieu of plane MVC.
CodeIgniter didnt implement HMVC natively,
but you can use this useful library in order to implement HMVC.
https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc
after setup
remember:that all your controllers should extends from MX_Controller in order to using this feature.
Go to the top of your View code and do it like this :
<?php
$this->load->model('MyModelName');
$MyFunctionReturnValue = $this->MyModelName->MyFunctionName($param));
?>
<div class="row">
Your HTML CODE
</div>

Categories