Codeigniter database not showing in view - php

I am learning CI and I'm trying to do this tutorial where you fetch data. My browser is just dumping this and nothing else
{entries}
{id}
{title}
{news}
{/entries}
Can you please help me figure this out? I'm pretty sure it has to do with my parser in the controller file
now this is my view:
<head>
<title>News Blog</title>
</head>
<body>
{entries}
<p>{id}</p>
<h3>{title}</h3>
<p>{news}</p>
{/entries}
</body>
Model
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class NewsModel extends CI_Model {
public function __construct() {
$this->load->database();
}
public function getNews($slug = FALSE){
$query = $this->db->get('news');
return $query->result_array();
}
}
and controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class News extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('newsModel');
}
public function index() {
$news = $this->NewsModel->getNews();
// I believe the issue is in the next few lines
$data['contactjs']=$this->parser->parse('templates/Javascript/contactjs',[],TRUE);
$data['bootCSS']=$this->parser->parse('templates/CSS/bootCSS',[],TRUE);
$data['CSS']=$this->parser->parse('templates/CSS/CSS',[],TRUE);
$data['jQuery']=$this->parser->parse('templates/Javascript/jQuery',[],TRUE);
$data['bootstrap']=$this->parser->parse('templates/Javascript/bootstrap',[],TRUE);
$template = '{id} {title} {news}';
$newsData = array('entries'=> $news);
$newsData = $this->parser->parse('pages/news', [], TRUE);
$data['news'] = $this->parser->parse('pages/news', $news, TRUE);
$this->load->view('templates/header', $data);
$this->load->view('pages/news');
$this->load->view('templates/footer');
}
}

Did you load the parser library? Try to output the $news variable, see if it contains some data. Also, check your application/log folder for more information. Maby there is a php error you're not seeing.
Next line of code should load your pages/news view just like any other view without the parser:
$this->load->view('pages/news'); // This view doesn't contain any parsed data now
I think you should create a temp variable and place all the data of all parsed views into it. Then load it in a view. To check, try to output the last variable and see if it contains any data like so;
echo "<pre>"; print_r($data['news']);

Related

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 - pass data to view

Ok I have a simple question I am using codeigniter frame work to create a simple blog. When I set up just a controller and a view I can print my database information (blog roll) to my view just fine. When I use the model controller view method i fail.
Here is what I would like to implement in to a method controller view setup.
my original view that works:
<?php
//is there an array from your search form?
if($_GET){
$books = $this->db->get('blog');//query the blog table in the database
if($books->num_rows() < 1)//are there clients to show?
{
echo 'There are no blog post'; //error message if no post
}
else
{
foreach(result() as $row)//loop through the blog
{
echo $row->title."<br>";//display each titles info
}
}
}
?>
This is what i have set for my New model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog_Model extends CI_Model {
function get($args = null)
{
$query = $this->db->get('blog');
return $query->result();
foreach(result() as $row)//loop through the books
}
function insert($data)
{
$this->db->insert('blog', $data);
}
function update($data,$id)
{
$this->db->where("id",$id);
$this->db->update('blog', $data);
}
function delete($id)
{
$this->db->where("id",$id);
$this->db->delete('blog');
}
}
this is my new controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog extends CI_Controller {
public function index()
{
$this->load->model('blog_model', 'blog');
$data['blogs'] = $this->blog->get();
$this->load->view('blog',$data);
}
}
I am not sure what to do for my new view? I just want to echo the blog roll to the view
Well you´re doing a foreach in the model after the return function.
So what you return is just this:
$query->result()
You may should do the foreach in the view, this would be better placed as a model just should just return and not process information. Best place would be in this case the controller or may view - depending on how strict you are.
I did not work with CodeIgniter for a while so may try this:
Controller:
class Blog extends CI_Controller
{
public function index()
{
$this->load->model('blog_model', 'blog');
$data['blogs'] = $this->blog_model->get()->result();
$this->load->view('blog',$data);
}
}
The View
Here goes some text...
<?php
foreach($blogs as $post)
{
echo $post['someData'];
echo $post['someData2'];
}
?>
After all this code...
May you want to lookup this (CodeIgniter Doc).
Hope this helps. Try to
Controller:
$data['blogs'] = $this->blog_model->get();
Even though you load the model in order to call its function you must pass its name.
Model:
Must always have result() or row() when query are applied.
Hope this helps in your endeavors

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>

pass two variables to main content

I need to pass two variables to a page and i'm not sure would i do it.
I need to tell it to load a specific view and also pass sql results to this view.
// template.php
<?php
$this->load->view('includes/header');
$this->load->view($main_content);
$this->load->view('includes/footer');
?>
// my controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MyController extends CI_Controller {
function query()
{
$this->load->model('search');
$data['main_content'] = 'query_results';
$sql['rows'] = $this->search->getAll();
$this->load->view('includes/template', $data, $sql); // no clue how to pass $sql to the view
}
}
?>
Thanks a lot in advance for your help.
You should change your function to
function query()
{
$this->load->model('search');
$data['main_content'] = 'query_results';
$data['rows'] = $this->search->getAll();
$this->load->view('includes/template', $data);
}
Now you can access your results in the view via the variable $rows.
You can find the reference here, section "Adding Dynamic Data".

Error when trying to load view in my_controller

Consider my code:
<?php
class MY_Controller extends Controller {
public function __construct()
{
parent::Controller();
}
function _displayPage($page, $data = array()) {
$this->load->view('structure/header', $data);
$this->load->view($page, $data);
$this->load->view('structure/footer', $data);
}
}
?>
page.php
<?php
class Page extends MY_Controller {
function __construct() {
parent::__construct();
}
function index() {
$data['content'] = array('title'=>'hello world');
$this->_displayPage('home', $data);
}
}
?>
Upon loading my page on my browser, I get this error:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Page::$view
Filename: libraries/MY_Controller.php
Line Number: 11
Does anyone know what I'm doing wrong?
Thanks
In your library My_Controller you should be using the parent keyword instead of $this.
your code should look like so:
class MY_Controller extends Controller
{
public function __construct()
{
parent::Controller();
}
function _displayPage($page, $data = array())
{
parent::load->view('structure/header', $data);
parent::load->view($page, $data);
parent::load->view('structure/footer', $data);
}
}
If I understand what you're trying to accomplish correctly, you're wanting to setup a template that includes your header view and footer view, but without calling header and footer views for each controller you use throughout your application. Here's what I've done to accomplish this.
First, create a new folder under your views, for this example we'll call it 'includes'. Inside the newly created includes folder, create three files, header.php, footer.php and template.php. Setup your header and footer appropriately and then edit your template.php to look as follows:
<?php echo $this->load->view('includes/univ_header'); ?>
<?php echo $this->load->view($main_content); ?>
<?php echo $this->load->view('includes/univ_footer'); ?>
Now, from your controller you can define what view you would like to set as your 'main_content'. For example, if you have home.php in your views folder and you want to wrap it with your header and footer you would do so in your controller as follows:
function index() {
$data['content'] = array('title'=>'hello world');
$data['main_content'] = 'home';
$this->load->view('includes/template', $data);
}
Hope this helps!

Categories