CodeIgniter pass variable from controller to view - php

Sorry if this question is already been answered, but i couldn't find an answer.
I want to pass a variable from my model to the controller and finally display it in the view.
I execute a query on the database and after that I count my results (via num_rows). Then I return the result.
public function countHighRisk(){
$this->db->select("ares_status");
$this->db->from("tbl_alert_result");
$this->db->join('tbl_status_standards', 'ares_status = sts_status_id');
$this->db->where('sts_status_risk', 3);
$query = $this->db->get();
return $query->num_rows();
}
After that i place the result in an array and pass the array to my view.
public function index()
{
$this->load->model('Alert_result_model');
$data['high'] = $this->Alert_result_model->countHighRisk();
$this->load->view('templates/head');
$this->load->view('templates/menu');
$this->load->view('pages/Dashboard', $data);
$this->load->view('templates/footer');
}
I get an error when I try to display the variable in the view.
<div class="col-xs-8 text-right">
<span> High Risk </span>
<h2 class="font-bold"><span class="count"><?= $high; ?></span></h2>
</div>
error: http://imgur.com/iHkYHiI
Thanks in advance.

Your whole idea of calling the views is wrong here. Please use it as follows:
Controller:
public function index()
{
$this->load->model('Alert_result_model');
$data['high'] = $this->Alert_result_model->countHighRisk();
$this->load->view('pages/Dashboard', $data);
}
View:
<? $this->load->view('templates/head'); ?>
<? $this->load->view('templates/menu'); ?>
<div class="col-xs-8 text-right">
<span> High Risk </span>
<h2 class="font-bold"><span class="count"><?= $high; ?></span></h2>
</div>
<? $this->load->view('templates/footer'); ?>
Also check what $this->Alert_result_model->countHighRisk(); is actually returning by doing print_r($this->Alert_result_model->countHighRisk();)

You can load a view into controller but do this way below
class Dashboard extends CI_Controller {
public function index() {
$this->load->model('Alert_result_model');
$data['high'] = $this->Alert_result_model->countHighRisk();
// Choose only one header examples:
$data['header'] = $this->load->view('header', Null, TRUE); // If No Data
$data['header'] = $this->load->view('header', $data, TRUE); // If Data
// Choose only one Footer examples:
$data['footer'] = $this->load->view('footer', Null, TRUE); // If No Data
$data['footer'] = $this->load->view('footer', $data, TRUE); // If Data
$this->load->view('dashboard', $data);
}
}
Dashboard View
<?php echo $header;?>
<?php foreach ($high as $low) { ?>
<?php echo $low['something'];?>
<?php }?>
<?php echo $footer;?>
If you have a header separate header controller and footer controller you will need HMVC if you are confused on user guide top right corner of default user guide in CI3 is a switch to more cleaner version.

please change
$this->load->view('pages/Dashboard', $data);
into
$this->load->view('pages/Dashboard', $data, true);
now it should work.

Related

Displaying the page titles based on the pages dynamically in codeigniter php

How to display page titles dynamically based on the pages displayed.
Hi i am having a site developed in codeigniter php but the problem is need to display page titles dynamically based on the pages.These pages titles should be fetched from database.Can anyone have any idea how to do this.
Controller:
public function index()
{
$config = array();
$config["base_url"] = base_url('testimonial/index');
$config['total_rows'] = $this->testimonial_model->record_count();//here we will count all the data from the table
$config['per_page'] = 6;//number of data to be shown on single page
$config['first_link'] = 'First';
$config['last_link'] = 'Last';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["records2"] = $this->testimonial_model->get_all_testimonials($config["per_page"], $page);
$data['records7'] = $this->index_model->get_all_banners();
$data["links"] = $this->pagination->create_links();//create the link for pagination
$data['mainpage'] = "testimonial";
$this->load->view('templates/template',$data);
}
Model:
function get_all_testimonials($limit, $start)
{
$this->db->limit($limit, $start);
$this->db->select('T.*');
$this->db->from('testimonials AS T');
$this->db->where(array('T.status'=>1));
$q = $this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<div class="container">
<div class="row testimonialpage">
<div class="col-md-12 testimonialpage">
<div class="col-md-9 testimonials" >
<div class="testimonialpagetext">
</div>
<?php if(isset($records2) && is_array($records2)):?>
<?php foreach ($records2 as $r):?>
<div class="testimonial1">
<div class="testimonialtext1">
<?php echo $r->description;?>
<ul class="founders">
<li class="founder"><?php echo $r->client_name;?></li>
<li class="founder"><?php echo $r->founder;?></li>
</ul>
</div>
</div>
<?php endforeach ;endif;?>
<div class="pagination"><?php echo $links; ?></div>
</div>
</div>
</div>
For Ex:: Your url is www.example.com/controller/register when you get uri segment(2) means you will get (register). based on this you can identify that you are on the register page. now you can find the title for register page from your database.
Every time i build an application with Codeigniter, i use a Class MY_Controller that extends CI_Controller, inside application/core like bellow:
class MY_Controller extends CI_Controller {
protected $view_data;
function __construct() {
//......
}
}
Any controller inside application/controllers will extend the MY_Controller instead of CI_Controller.
Now in the constructor of MY_Controller you can do something like:
$page = $this->uri->segment(2); (2 or 3 or 4 etc, depends on your structure)
Load your model, execute your query and add the result in $this->view_data like:
$pageTitle = $this->your_model->getPageTitle($page);
$this->view_data['page_title'] = $pageTitle['page_title'];
Example of getPageTitle in your model:
public function getPageTitle($page) {
$qry = $this->db->select('page_title')
->from('pages')
->where('page', $page)
->get();
if ($qry->num_rows() > 0)
return $qry->row_array();
return false;
}
Watch out the sample names i gave, you should change those!
To load your view, pass the variable $this->view_data as parameter and in your view do something like
<title><?= $page_title ?></title>

Undefined variable: data

i am still fresher in PHP MVC architecture. here i am trying to list the data in my database table through the model view controller. i am phase this error to fetch the data . i am doing edit my data,. so edit function is not working .
test-table name
there are few fields to get the data username and email..
please help me to solve this query
here is my Model file.
public function getAllRecords()
{
$this->load->library("database");
$q = $this->db->get("test");
if($q->num_rows() > 0)
{
return $q->result();
}
return array();
}
Here is my Controller file
public function index()
{
$this->load->model("testmodel");
$data['records'] = $this->model->getAllRecords();
$this->load->view("edit",$data);
}
and it is my View/edit.php file
<tr>
<?php
if (is_array($data)){
foreach($data as $row):
?>
<tr>
<td><?=$row->id?></td>
<td><?=$row->uname?></td>
<td><?=$row->email?></td>
<td> <img src="../edit.png" alt=""/> </td>
<td> <img src="../delete.png" alt=""/> </td>
</tr>
Controller
Change
$data['records'] = $this->model->getAllRecords();
to
$data['records'] = $this->testmodel->getAllRecords();
View
Use $records instead of $data
in your view file use $records instead of $data
<?php
if (is_array($records)){
foreach($records as $row):
?>
when you pass a data from controller to view say
$data['name'] = 'max';
$this->load->view("edit",$data);
in view you can access it with variable $name
Controller:
public function index()
{
$this->load->model("testmodel");
$data['records'] = $this->model->getAllRecords();
$this->load->view("edit",array('data'=>$data));
}
This will work for sure.
Enjoy!

inserting a value in codeigniter shows no error

I am trying to insert a row to the db using codeigniter.
Model-post.php
class Post extends CI_Model{
function get_posts($num=20, $start=0){
$this->db->select()->from('posts')->where('active',1)->order_by('date_added','desc')->limit($num,$start);
$query=$this->db->get();
return $query->result_array();
}
function get_post($postid){
$this->db->select()->from('posts')->where(array('active' => 1, 'postID'=>$postid))->order_by('date_added','desc');
$query=$this->db->get();
return $query->first_row('array');
}
function insert_post($data){
$this->db->insert('posts',$data);
return $this->db->return_id();
}
Controller-posts.php
class Posts extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('post');
}
function index(){
$data['posts'] = $this->post->get_posts();
$this->load->view('post_index', $data);
}
function post($postid){
$data['post']=$this->post->get_post($postid);
$this->load->view('post',$data);
}
function new_post(){
if($_POST){
$data =array(
'title'=>$_POST['title'],
'post'=>$_POST['post'],
'active'=>1
);
$this->post->insert_post($data);
redirect(base_url());
}
else{
$this->load->view('new_post');
}
}
View-new_post.php
<form action="<?php base_url(); ?>posts/new_post" method="action">
<p>Title: <input type="text" name="title"></p>
<p>Description: <input type="textarea" name="post"></p>
<input type="submit" value="Add post">
</form>
Index view-post_index.php
foreach ($posts as $post) { ?>
<div id-="container">
<div><h3><?php echo $post['title']; ?> </h3>
<?php echo $post['post']; ?>
</div>
</div>
<?php
}
The index page shows all the posts from db. On clicking the title it takes to post.php view to show the respective data. This part is fine.
While trying to add a new post in new_post.php it is not reflecting in the db nor showing any error. Also I used redirect_url to redirect to the index page after inserting. So it shows the same available posts. On clicking the title it keeps on adding posts/post to the url repeatedly. Clicking the title once after redirecting the url shows
http://localhost/Codeigniter/posts/posts/post/1
Again on clicking the title it adds
http://localhost/Codeigniter/posts/posts/post/post/1
Can anyone help me? Thanks!
There are numerous issues across the entire application. These are what I found:
Views
Two problems in your new_post view.
You are not echoing out your base_url . You need to replace your form's action attribute.
the method attribute should either have post or get. In this case it should be post
Change it like this:
From this:
<form action="<?php base_url(); ?>posts/new_post" method="action">
To this:
<form action="<?= base_url(); ?>posts/new_post" method="post">
alternatively you can do this:
<form action="<?php echo base_url(); ?>posts/new_post" method="post">
Controller
In your posts controller, your new_post() function should be like this:
function new_post() {
if ($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'post' => $this->input->post('post'),
'active' => 1
);
$id = $this->post->insert_post($data);// this is the id return by your model.. dont know what you wann do with it
// maybe some conditionals checking if the $id is valid
redirect(base_url());
} else {
$this->load->view('new_post');
}
}
Model
function insert_post() should not have $this->db->return_id();, instead it should be $this->db->insert_id();
in your model
function insert_post($newpost){
$this->db->insert('posts',$newpost);
// check if the record was added
if ( $this->db->affected_rows() == '1' ) {
// return new id
return $this->db->insert_id();}
else {return FALSE;}
}
any user input must be validated. if you are using Codeigniter then use its form validation and use its input library like:
$this->input->post('title')
an example for blog posts are in the tutorial https://ellislab.com/codeIgniter/user-guide/tutorial/create_news_items.html
otherwise in your controller -- check if the new post id did not come back from the model -- if it did not come back then just go to an error method within the same controller so you don't lose the php error messages.
if ( ! $postid = $this->post->insert_post($newpost); ){
// passing the insert array so it can be examined for errors
$this->showInsertError($newpost) ; }
else {
// success now do something else ;
}

codeigniter join query, display data to view

im new to codeigniter & php, and i have some question about join() function.
i have this model:
public function get_categorie()
{
$this->db->select('*');
$this->db->from('foxCategory');
$this->db->join('foxAnnunci', 'foxCategory.id = foxAnnunci.id_foxCategory');
$query = $this->db->get();
}
this controller:
public function index()
{
$data['category']= $this->annunci_model->get_categorie();
$data['annunci'] = $this->annunci_model->get_annunci();
$data['titolo'] = 'Elenco annunci';
$this->load->view('templates/header', $data);
$this->load->view('annunci/index', $data);
$this->load->view('templates/footer');
}
and this view
<h2><?php echo $value['titolo'] ?></h2>
<div id="main">
<code>Data di creazione: <?php echo $value['creato_il'] ?></code><br />
<?php echo $value['descrizione'] ?>
</div>
<p>Guarda annuncio || <p><?php echo $category['category']['titolo'] ?></p></p>
i want to display the name of category as link (classic for blog category function), but this code show nothing, what is the problem?

FuelPHP basics, using Model result in View

I am a little confused using fuelPHP 1.7.
The controller
class Controller_Website extends Controller
{
public function action_index()
{
// http://fuelphp.com/docs/general/views.html
$data = Website::get_results();
//var_dump($data) // (data is found here);
$views = array();
$views['head'] = View::forge('common/head', $data);
$views['header'] = View::forge('common/header', $data);
$views['sidebar'] = View::forge('common/sidebar', $data);
$views['content'] = View::forge('common/content', $data);
$views['footer'] = View::forge('common/footer', $data);
// return the rendered HTML to the Request
return View::forge('website', $views)->render();
}
}
The model
class Website extends \Model
{
public static function get_results()
{
// Database interactions
$result = DB::select('menu', 'url', 'title', 'text')
->from('aaa_website')
->where('id', '=', 1035)
->and_where('visible', '1')
->execute();
return $result;
}
}
All well sofar. Data is queried and found in the controller. What I am trying to accomplish is to use the data in my:
(nested) view
<html>
<head>
<?php echo $head; ?>
</head>
<body>
<header>
<div class="container">
<?php echo $header; ?>
</div>
</header>
<div class="row">
<div class="container">
<div class="col-md-4">
<?php echo $sidebar; ?>
</div>
<div class="col-md-8">
<?php echo $content; ?>
</div>
</div>
</div>
<footer>
<div class="container">
<?php echo $footer; ?>
</div>
</footer>
</body>
</html>
Head view (nested):
<title><?php echo $title; ?></title>
Content view (nested):
<h1><?php echo $title; ?></h1>
<div class="welcome_user"><?php echo $text; ?></div>
And so on.
The variables in the view in this example are not available because they are not explicitly set in the controller. Do they have to be set explicitly or is passing the data object also possible? If so, how do I access this objects data in the right way? FuelPHP is lacking good examples here and I am stuck now.
How do I do it?
The view data is converted from array indexed to view variable named. So:
View::forge('something', array('param' => 'value'));
Will correspond to the following view:
<h1><?=$param?></h1>
Where things are going wrong is is that you pass the plain DB result to the view. You'd need to get the first result from the database result, like this:
class Website extends \Model
{
public static function get_results()
{
// Database interactions
$result = DB::select('menu', 'url', 'title', 'text')
->from('aaa_website')
->where('id', '=', 1035)
->and_where('visible', '1')
->as_assoc()
->execute()
->to_array();
return reset($result);
}
}
Note that I've first used ->to_array() to convert the result object to an array, then reset() to get the first result. I've also added ->as_assoc() to make sure you get an array result, ->as_object() would give you a stdClass instance.

Categories