Codeigniter Message: Undefined variable: infos - codeigniter

I am a newbie in CI. I used MY_Controller.php as main controller. I could open the ajax as the div#page loader. Now , My problem is although I load /about page, I get the database entries for the services model. How can i get the about table for the about controller ?
..
function render_page($view) {
if( ! $this->input->is_ajax_request() )
{
$this->load->view('templates/header', $this->data);
}
$this->load->view($view, $this->data);
if( ! $this->input->is_ajax_request() )
{
$this->load->view('templates/menu');
$this->load->view('templates/footer', $this->data);
}
}..
My services_model:
class Services_model extends CI_Model {
function getAll() {
$q = $this->db->get('services');
if($q->num_rows() > 0){
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
}
My home controller :
public function view($page = 'home')
{
$this->load->helper('text');
$this->data['records']= $this->services_model->getAll();
if ( ! file_exists('application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->render_page('pages/'.$page,$data);
}
When I use them in the home view there is no problem I can see the services_table :
<ul class="blog-medium">
<?php foreach($records as $row): ?>
<li>
<div class="blog-medium-text">
<h1><?php echo $row->title; ?></h1>
<p class="blog-medium-excerpt"><?php echo $row->content; ?><br />
Devamını Okumak için →</p>
</div>
<?php endforeach ?>
I want to use the same way in about page.
About_model:
class About_model extends CI_Model {
function getAll() {
$q = $this->db->get('abouts');
if($q->num_rows() > 0){
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
}
About controller :
public function view($page = 'about')
{
$this->load->helper('text');
$this->data['records']= $this->about_model->getAll();
if ( ! file_exists('application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->render_page('pages/'.$page,$data);
}
And this is my view file of about :
<div id="content">
<?php foreach($infos as $row): ?>
<h3 style="text-align: center;"> <?php echo $row->title; ?></h3>
<div class="hr"> </div>
<?php echo $row->content; ?>
<?php endforeach; ?>
I get the error telling me :
Severity: Notice
Message: Undefined variable: infos
Filename: pages/about.php
Line Number: 3
Why cant i get the abouts table?

You are calling a variable $infos in your foreach, but it is never passed in as a variable to your view.
Read the docs about Adding Dynamic Data to the View
You will either need to set $data['infos'] to something or, and I'm guessing this what you intended, use $records in your foreach
The above answers your specific, but after you provided the repo for your source, there are issues you are struggling with. I highly suggest you read through the entire documentation, staring with the Introduction: Getting Started, continuing to the Tutorials and then General Topics.
The reason you are having problems here, you have your routes.php setup to that everything is routed into the Home controller executing the view method. This method, while it accepts the page you want to see is always returning a fetch of the services model. Your other controllers are not getting executed at all. Based on your controller setup, if you would just remove the custom route, http://theurl/about would route to the About Controller. The default method to be loaded is index so if you change view to index, then it would be displayed by default.

Related

Fetching and updating data from a database

I want to fetch and update data from database using codeigniter. I am facing some problem. This is my code:
This is my Model by the name of Update_site_model.
<?php
class update_site_model extends CI_Model{
function show_invoice_id($data) {
$this->db->select('*');
$this->db->from('invoices');
$this->where('invoiceId', $data);
$query = $this->db->get();
$result = $query->result();
return $result;
//Update Query For Selected Invoice.
function update($id,$data) {
$this->db->where('invoiceId',$id);
$this->db->update('invoices',$data);
}
}
?>
This is my Controller by the name of update site.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Update_site extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->view('includes/header');
$this->load->view('site/update');
$this->load->view('includes/footer');
//load the model
$this->load->model('update_site_model');
}
function show_invoices() {
$id = $this->uri->segment(3);
$data['single_invoice'] = $this->update_site_model->show_invoice_id($id);
$this->load->view('site/update', $data);
}
function update() {
$id = $this->input->post('invoiceId');
$data = array(
'Date' => $this->input->post('invoiceDate'),
'Client' => $this->input->post('invoiceClient'),
'Amount' => $this->input->post('invoiceAmount'),
'Status' => $this->input->post('invoivceStatus')
);
$this->update_site_model->update($id, $data);
}
}
This is my view by the name of update. it is inside a folder by the name of site.
<div id="content">
<ol>
<?php foreach ($invoices as $invoice): ?>
<li><?php echo $invoice->invoiceId; ?></li>
</ol>
<?php endforeach; ?>
</div>
and this is the problem.
Severity: Notice
Message: Undefined variable: invoices
Filename: site/update.php
Line Number: 11
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: site/update.php
Line Number: 11
Please help me to solve the problem.
Look at this in your controller:
$data['single_invoice'] = $this->update_site_model->show_invoice_id($id);
and now look at this in your view:
<?php foreach ($invoices as $invoice): ?>
did you got your mistake..?
no..?
let me tell you , since you are storing the database result in $data['single_invoice'] you should access this by $single_invoice in the view.
so correct usage in your view is :
<?php foreach ($single_invoice as $invoice): ?>
and next time when you ask any question give appropriate title to it.

passing multiple queries to view with codeigniter

I am trying to build a forum with Codeigniter.
So far i have the forums themselves displayed and the threads displayed, based on the creating dynamic news tutorial.
But that is 2 different pages, i need to obviously display them into one page, like this:
Forum 1
- thread 1
- thread 2
- thread 3
Forum 2
- thread 1
- thread 2
etc.
And then the next step is obviously to display all the posts in a thread. Most likely with some pagination going on. But that is for later.
For now i have the forum controller (slimmed version):
<?php
class Forum extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('forum_model');
$this->lang->load('forum');
$this->lang->load('dutch');
}
public function index()
{
$data['forums'] = $this->forum_model->get_forums();
$data['title'] = $this->lang->line('title');
$data['view'] = $this->lang->line('view');
$this->load->view('templates/header', $data);
$this->load->view('forum/index', $data);
$this->load->view('templates/footer');
}
public function view($slug)
{
$data['forum_item'] = $this->forum_model->get_forums($slug);
if (empty($data['forum_item']))
{
show_404();
}
$data['title'] = $data['forum_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('forum/view', $data);
$this->load->view('templates/footer');
}
}
?>
And the forum_model (also slimmed down)
<?php
class Forum_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_forums($slug = FALSE)
{
if ($slug === FALSE)
{
$query= $this->db->get('forum');
return $query->result_array();
}
$query = $this->db->get_where('forum', array('slug' => $slug));
return $query->row_array();
}
public function get_threads($forumid, $limit, $offset)
{
$query = $this->db->get_where('thread', array('forumid', $forumid), $limit, $offset);
return $query->result_array();
}
}
?>
And the view file
<?php foreach ($forums as $forum_item): ?>
<h2><?=$forum_item['title']?></h2>
<div id="main">
<?=$forum_item['description']?>
</div>
<p><?=$view?></p>
<?php endforeach ?>
Now that last one, i would like to have something like this:
<?php foreach ($forums as $forum_item): ?>
<h2><?=$forum_item['title']?></h2>
<div id="main">
<?=$forum_item['description']?>
</div>
<?php foreach ($threads as $thread_item): ?>
<h2><?php echo $thread_item['title'] ?></h2>
<p><?=$view?></p>
<?php endforeach ?>
<?php endforeach ?>
But the question is, how do i get the model to return like a double query to the view, so that it contains both the forums and the threads within each forum.
I tried to make a foreach loop in the get_forum function, but when i do this:
public function get_forums($slug = FALSE)
{
if ($slug === FALSE)
{
$query= $this->db->get('forum');
foreach ($query->row_array() as $forum_item)
{
$thread_query=$this->get_threads($forum_item->forumid, 50, 0);
}
return $query->result_array();
}
$query = $this->db->get_where('forum', array('slug' => $slug));
return $query->row_array();
}
i get the error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: models/forum_model.php
Line Number: 16
I hope anyone has some good tips, thanks!
Lenny
*EDIT***
Thanks for the feedback.
I have been puzzling and this seems to work now :)
$query= $this->db->get('forum');
foreach ($query->result() as $forum_item)
{
$forum[$forum_item->forumid]['title']=$forum_item->title;
$thread_query=$this->db->get_where('thread', array('forumid' => $forum_item->forumid), 20, 0);
foreach ($thread_query->result() as $thread_item)
{
$forum[$forum_item->forumid]['thread'][]=$thread_item->title;
}
}
return $forum;
}
What is now next, is how to display this multidimensional array in the view, with foreach statements....
Any suggestions ?
Thanks
You are using row_array() hence your error, change your get_forums() to:
$thread_query=$this->get_threads($forum_item['forumid'], 50, 0);
But I believe you should actually be using result_array() since you want a list of all forums.

Flash messanger in zf2

How can i use flash messenger in zend freamwork 2? Session documentation is not yet. Anyone know it? But session libraries are there.
Update :
Zend Framework new release added FlashMessenger View Helper , found in path /library/Zend/View/Helper/FlashMessenger.php
FlashMessenger.php
Old answer :
I have written a custom view helper, for printing flash messages
In /module/Application/Module.php
public function getViewHelperConfig()
{
return array(
'factories' => array(
'flashMessage' => function($sm) {
$flashmessenger = $sm->getServiceLocator()
->get('ControllerPluginManager')
->get('flashmessenger');
$message = new \My\View\Helper\FlashMessages( ) ;
$message->setFlashMessenger( $flashmessenger );
return $message ;
}
),
);
}
Create a custom view helper in /library/My/View/Helper/FlashMessages.php
namespace My\View\Helper;
use Zend\View\Helper\AbstractHelper;
class FlashMessages extends AbstractHelper
{
protected $flashMessenger;
public function setFlashMessenger( $flashMessenger )
{
$this->flashMessenger = $flashMessenger ;
}
public function __invoke( )
{
$namespaces = array(
'error' ,'success',
'info','warning'
);
// messages as string
$messageString = '';
foreach ( $namespaces as $ns ) {
$this->flashMessenger->setNamespace( $ns );
$messages = array_merge(
$this->flashMessenger->getMessages(),
$this->flashMessenger->getCurrentMessages()
);
if ( ! $messages ) continue;
$messageString .= "<div class='$ns'>"
. implode( '<br />', $messages )
.'</div>';
}
return $messageString ;
}
}
then simple call from layout.phtml , or your view.phtml
echo $this->flashMessage();
Let me show example of controller action
public function testFlashAction()
{
//set flash message
$this->flashMessenger()->setNamespace('warning')
->addMessage('Mail sending failed!');
//set flash message
$this->flashMessenger()->setNamespace('success')
->addMessage('Data added successfully');
// redirect to home page
return $this->redirect()->toUrl('/');
}
In home page, it prints
<div class="success">Data added successfully</div>
<div class="warning">Mail sending failed!</div>
Hope this will helps !
i have written a post about this some time ago. You can find it right here
Basically you use it just the same like earlier.
<?php
public function commentAction()
{
// ... display Form
// ... validate the Form
if ($form->isValid()) {
// try-catch passing data to database
$this->flashMessenger()->addMessage('Thank you for your comment!');
return $this->redirect()->toRoute('blog-details'); //id, blabla
}
}
public function detailsAction()
{
// Grab the Blog with given ID
// Grab all Comments for this blog
// Assign the view Variables
return array(
'blog' => $blog,
'comments' => $comments,
'flashMessages' => $this->flashMessenger()->getMessages()
);
}
Then in your .phtml file you do it like this:
// details.phtml
<?php if(count($flashMessages)) : ?>
<ul>
<?php foreach ($flashMessages as $msg) : ?>
<li><?php echo $msg; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Obviously this isn't all too handy, as you have to do this for every single .phtml file. Therefore doing it within the layout you have to do it at best like the following:
<?php
// layout.phtml
// First get the viewmodel and all its children (ie the actions viewmodel)
$children = $this->viewModel()
->getCurrent()
->getChildren();
$ourView = $children[0];
if (isset($ourView->flashMessages) && count($ourView->flashMessages)) : ?>
<ul class="flashMessages">
<?php foreach ($ourView->flashMessages as $fMessage) : ?>
<li><?php echo $fMessage; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
If you need further description, please see my blog, but i guess the code itself is pretty clear (apart frmo the layout.phtml example). Alternatively you're always free to write your own view helper to have it look a little cleaner inside your view-templates.
How to grab Flashmessenger’s messages in a View Helper – sharing code as requested by Sam.
The View helper should implement the ServiceManagerAwareInterface interface and related methods. The plugin will now have access to a Service Manager which we can use to get the Service Locator and ultimately access to the Flash Messenger.
I’ve not touched this code since I initially wrote it – so there may be a more elegant way of doing this.
protected function getMessages()
{
$serviceLocator = $this->getServiceManager()->getServiceLocator();
$plugin = $serviceLocator->get('ControllerPluginManager');
$flashMessenger = $plugin->get('flashmessenger');
$messages = $flashMessenger->getMessages();
// Check for any recently added messages
if ($flashMessenger->hasCurrentMessages())
{
$messages += $flashMessenger->getCurrentMessages();
$flashMessenger->clearCurrentMessages();
}
return $messages;
}
And calling getMessages() from within the plugin should return an array of messages that can be passed to a partial and rendered.
Add code below to the view to render error messages:
<?php echo $this->flashmessenger()
->setMessageOpenFormat('<div class="alert alert-danger"><ul%s><li>')
->setMessageCloseString('</li></ul></div>')
->render('error')
; ?>
In previous request, make sure you created an error message by running code below in your controller:
$this->flashmessenger()->addErrorMessage('Whops, something went wrong...');

How to pass multiple variable data from model to view

Could you please tell me how my model,controller and view should look like if I want to pass the following variable data($amount1, $amount2, $amount3) to my view file via controller from my model.
case 1: $amount1=100;
case 2: $amount2=500;
case 3: $amount3=1000;
I want to have the variables in a way that I don't have to echo them in any { } example:
foreach ($records as $row){ $i++; ?>
// I don't want to echo those inside in this.
// I want to echo it like this way- <? echo $amount1;?>
}
Thanks in Advance :)
If you pass an array of data from your controller to your view you can access each element as a variable in the view. Here is an example of what I mean:
model:
class Model extends CI_Model
{
public function get_data()
{
$data = array(
'amount1' => 100,
'amount2' => 500,
'amount3' => 1000,
);
return $data;
}
}
controller:
class Controller extends CI_Controller
{
public function index()
{
// get data from model
$data = $this->model->get_data();
// load view
$this->load->view('view', $data);
}
}
view:
<h1><?php echo $amount1; ?></h2>
<p><?php echo $amount2; ?></p>
<!-- etc... -->
I have found a solution myself. I just wanted to share so that it can help others. So here it is..
Your model should look like following :
function net_income(){
$data['amount1']=50;
$data['amount2']=100;
return json_encode($data);
}
Your controller:
function add(){
$this->load->model('mod_net_income');
$json = $this->mod_net_income->net_income();
$obj = json_decode($json);
$data['amount1']= $obj->{'amount1'};
$this->load->view('your_viewfile_name',$data);
}
And then in your view file: just
<? echo "$amount" ; ?>
Thanks :)

Unable to load database table contents with ActiveRecord

I'm new to CodeIgniter and am having trouble loading the contents of a simple database table (named 'entries') with the ActiveRecord syntax--I'm getting a blank page.
Here is my controller:
class Blog extends CI_Controller {
function Blog() {
parent::__construct();
}
function all() {
$this->load->model('Entries');
$data['rows'] = $this->Entries->load_all();
$this->load->view('view_all', $data);
}
}
Model:
class Entries extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function load_all() {
$query => $this->db->get('entries');
return $query->result();
}
}
View:
<ol>
<? foreach($rows as $row): ?>
<li><?= $row->title ?></li>
<? endforeach; ?>
</ol>
NOTE: I can get it to work if I change the load_all() function in my model to:
function load_all() {
$sql = "SELECT * FROM entries";
$query = $this->db->query($sql);
return $query->result_array();
}
And my view to:
<ol>
<? foreach($rows as $row): ?>
<li><?= $row['title'] ?></li>
<? endforeach; ?>
</ol>
Any thoughts why the ActiveRecord syntax isn't working?
FYI: CodeIgniter 2.0, MySQL, PHP 5.3.2. Oh and the $active_record setting in config/database.php is TRUE.
Thanks.
In your load_all() function you have a misplaced '=>' after $query. It should be a '='
$query = $this->db->get('entries');
Then you can return your $query object.
return $query->result();
On another note, you don't need to use capital letters when calling your model. Even though the model name may be capitalized, the object function call is allowed to be lowercase. Your code won't break if you use capital, you just don't need to.
I think you need to tell your view that the query result needs to be extracted:
<ol>
<? foreach($rows->result() as $row): ?>
<li><?= $row->title ?></li>
<? endforeach; ?>
</ol>

Resources