Undefined variable: query - codeigniter - codeigniter

I am getting the message:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: query
Filename: views/main.php
Line Number: 12
This is the code for my controller:
function get_all(){
$this->load->model('book_model');
$this->load->library('table');
$this->load->helper('html');
$data['query'] = $this->books_model->books_getall();
$this->load->view('main', $data);
}
And this is my view:
<h1> List of books in library</h1>
<table border="1"/>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Information</th>
<th>Publisher</th>
<th colspan="2">Action</th>
</tr>
<?php
if(is_array($query)){
foreach ($query as $row){
echo "<tr>";
echo "<td>".$row->id."</td>";
echo "<td>".$row->title."</td>";
echo "<td>".$row->author."</td>";
echo "<td>".$row->information."</td>";
echo "<td>".$row->publisher."</td>";
echo "<td>".anchor('book/input'.$row->id,'Edit')."</td>";
echo "<td>".anchor('book/delete'.$row->id,'Delete')."</td>";
echo "</tr>";
}
}
?>
</table>
Thanks in advance for any help
Edit: This is my model code:
function get_all(){
$this->load->database();
$query = $this->db->get('books');
return $query->result();
}

From what I can see, line 12 appears to be this line:
if(is_array($query)){
And the error message is saying that $query is undefined. When you pass $data['query'] through to the view, that becomes $query.
I note your model is also returning $query->result(). This is not correct - result() should be used inside a loop to loop through the results, and you can use num_rows() to test for more than zero results, as in this example:
Model
function example()
{
$query = $this->db->get('books');
return $query;
}
Controller
$this->load->model('book_model');
$this->load->library('table');
$this->load->helper('html');
$data['query'] = $this->books_model->books_getall();
$this->load->view('main', $data);
View
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
// Do stuff here on each $row
}
}
I suggest you take a look at this part of CodeIgniter's documentation, which is actually very good.

Related

Want to display db value in my page. The Add and view should in one page

public function unit_list()
{
//Redirect in case of session out
if (!$this->session->userdata ( 'user_id' )) {
redirect ( $this->config->base_url (), 'refresh' );
return false;
}
$this->load->model('Unit_model');
$arrWhere = array("vchr_unit_status"=>"A");
$data ["unit"]=$this->Unit_model->get_all($arrWhere);
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('unit/manage',$data);
$this->load->view('includes/footer');
}
This is my controller . The unit_list is the function i wrote to get all data from db and view that in my view page
class Unit_model extends CI_Model{
protected $strTableName = 'suc_unit';
function __construct(){
parent::__construct ();
$CI = &get_instance();
$this->db->from($this->strTableName);
}
/**
*
*/
function get_all($arrWhere)
{
$this->db->where($arrWhere);
$q1 = $this->db->get();
$result = $q1->result_array();
return $result;
}
This is my model
<table id="tblListOfUnits" class="table table-bordered table-striped">
<tr>
<th style="width: 10px">Sl No</th>
<th>Unit Name</th>
<th>Unit Symbol</th>
</tr>
<?php
if(!isset($unit)){
$count = 1;
foreach ($unit as $key => $units) {
?>
<tr id="tr_<?php echo $units->pk_int_unit_id; ?>">
<td id="tdUntSlNo_<?php echo isset($units) ? $units['int_no_decimal']: ' '; ?>><a href="javascript:unitEdit(<?php echo $unit->pk_int_unit_id; ?>)" ><?php echo $count; ?>.</a></td>
<td id="tdUntNme_<?php echo $units->pk_int_unit_id; ?>"><a href="javascript:unitEdit(<?php echo $unit->pk_int_unit_id; ?>)" ><?php echo $unit->vchr_unit_name; ?></a></td>
<td id="tdUntSymbl_<?php echo $units->pk_int_unit_id; ?>"><a href="javascript:unitEdit(<?php echo $unit->pk_int_unit_id; ?>)" ><?php echo $unit->vchr_unit_symbol; ?></a></td>
</tr>
<?php
$count ++;
}
}?>
</table>
This is my view page. please help me to view all the data in my view page. Im new to codeigniter so i dont know how to use get_all function to view the data in my page.
CodeIgniter allows you to pass the data to the view in a couple of ways. First, if you would simply use the second parameter of the view method, then your data would be available as $unit in the view.
In your code, it seems that you are doing that. That means that in your unit/manage.php view, the result of your query should be available as $unit.
A couple of things though. When you load a model, calls to that model are lowercased.
$this->unit_model->get_all( $arrWhere );
It may not matter, but that line should be:
$data["unit"] = $this->unit_model->get_all( $arrWhere );
I want to point out that in your model's method, you are assuming that you will always have a result, and that's not OK. You need to make sure there's a result before trying to return it. Also, you need to provide a table name to get():
function get_all( $arrWhere )
{
// Make sure $arrWhere is an array
if( ! is_array( $arrWhere ) )
return FALSE;
$this->db->where( $arrWhere );
// Make sure you set the table name!
$q1 = $this->db->get( $this->strTableName );
// Make sure there is a result set!
if( $q1->num_rows() > 0 )
return $q1->result_array();
return FALSE; // or NULL, or array(), or whatever you want.
}
Sure, you are trying to set the table in the constructor of the model, but that would only work for the first query to the database. That's not right, and you should avoid that because typically you don't create a model just for a single query.
function __construct()
{
parent::__construct();
// If you are in a CodeIgniter model, you don't need this line
// $CI = &get_instance();
// This is bad. Don't do this ever.
// $this->db->from($this->strTableName);
}
Now in your view you have a problem. $unit will ALWAYS be set, so when you do this:
if( ! isset( $unit ) ) ...
You will never enter that block of code. What you should be doing there is:
if( ! empty( $unit ) ) ...
In your foreach loop, this code will throw an error:
$units->pk_int_unit_id
It's because you are returning an array of arrays from your db call, so it should be:
$units['pk_int_unit_id']
You've got other instances where you're trying to use an object that is actually an array. Basically anywhere that you have $units-> it should be $units['...'].
If you wany to use an object instead of an array, then inside get_all() you should use:
return $q1->result();
Because result_array() is an array of arrays, but result() is an array of objects.
Anyways, hope this helps.

Undefined variable, how to retrieve data from database in codeigniter?

My model is:
function get_all_pages(){
$query= $this->db->query("SELECT Title FROM news");
return $query->result_array();
}
My view is:
<table cellpadding="0" cellspacing="0">
<tr>
<th>Title</th>
</tr>
<?php
$count=1;
if(!empty($content)) {
foreach ($content as $content1)
{
?>
<tr>
<td align="left"><?php echo $content1['Title']; ?></td>
</tr>
<?php
}
} else{?>
<tr>
<td align="center" colspan="4"><?php echo "No Record Added Yet!!!";?></td>
</tr>
<?php }?>
</table>
My controller is:
public function manage_news()
{
$this->load->model('users_model');
$result_nb = $this->users_model->get_all_pages();
$data['content'] = $result_nb;
$data['page_title']="Manage Pages";
$this->load->view("manage_news",$data);
}
I am using codeigniter. my exact error is:
Call to undefined method users_model::get_all_pages()
how can i fix this error? i want the title row data to appear in a table (from the db)
Q: use Correct naming structure for CI? Which version do u use?
Filename
models/user_model.php
Examples (for demo purpose)
<?php
class User_model extends CI_Model {
// example one
function get_all_pages() {
$query = $this->db->query("SELECT Title FROM news")->result_array();
return ( is_array($query) && sizeof($query) > 0 ? $query : FALSE);
}
// example second
function get_all_pages_second() {
$data = FALSE;
$query = $this->db->query("SELECT Title FROM news");
if ($query->num_rows() > 0){
$data = $query->result_array();
}
return $data;
}
// example third
function get_all_pages_third() {
$data = FALSE;
$query = $this->db->select('Title')->get('news');
if ($query->num_rows() > 0){
$data = $query->result_array();
}
return $data;
}
}

codeigniter grabbing array from database

I'm new to codeigniter and followed the guides but seem to be missing something. I have a simple database with customer records in it. My first goal in codeigniter is to simple list all my customers.
here is my controller:
public function index()
{
$this->load->model('HomeModel'); //loads the HomeModel model
$data = $this->HomeModel->function1(); //loads the function (function1) from the model
$this->load->view('index', $data);
}
Here is my model:
public function function1()
{
$query = $this->db->get('work_orders');
return $query->result();
}
here is my view:
<table class="table table-bordered table-striped table-highlight" id="invoice-details">
<thead>
<tr>
<th>Work Order ID</th>
<th>Status</th>
<th>Description</th>
</tr>
</thead>
<?php
foreach ($data->result() as $row);?>
<tr class="even gradeC">
<td><a href="/WorkOrders/viewWo/<?php echo $row['id']; ?>">
<?php echo $row['id']; ?></a></td>
<td><?php echo $row['status']; ?></td>
<td><?php echo Logic\System\Lib\Helper::trunc(htmlentities($row['description']), 8); ?></td>
</tr>
<?php endforeach; ?>
</table>
Change on model :
public function function1()
{
$query = $this->db->get('work_orders');
//return $query->result();
return $query->result_array();
}
Change on controller :
public function index()
{
$this->load->model('HomeModel');
//$data = $this->HomeModel->function1();
$data['result'] = $this->HomeModel->function1();
$this->load->view('index', $data);
}
Change on view :
//foreach ($data->result() as $row);
if(is_array($result)&&!empty($result))
foreach ($result as $row);
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function. Here is an example using an array:
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('blogview', $data);
Views : Codeigniter User Guide
And Since you are using array on your view like $row['id'], you got to use result_array on model to return result set array:
This function returns the query result as a pure array, or an empty array when no result is produced. Typically you'll use this in a foreach loop, like this:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
Generating Query Results : Codeigniter
You can use $this->db->join();
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
Produces:
SELECT * FROM blogs
JOIN comments ON comments.id = blogs.id
Go through active record class guide .
Active Record Class
In ur controller,u must pass the values as subarray of data array$data['result'].After which u can simply call it in view as $result .
Controller
$data['result'] = $this->HomeModel->function1();
And In view,
foreach ($result as $row){
<?php echo $row->id; ?>
..
}

accessing array in array data pass from controller to view of codeigniter

I have this following code in my controller. I want to print the data i have my array.. should it be double forloop or foreach?
CONTROLLER:
public function index()
{
$in_cart = array();
if (!isset($_SESSION['cartProducts'])){
$in_cart['list'] = "No Products";
}
else{
foreach ($_SESSION['cartProducts'] as $key => $value) {
$in_cart[$key] = $this->shopmod->get_one_data($key);
}
$cart['list'] = $in_cart;
}
$this->load->vars($cart);
$data['cart'] = $this->load->view('shop/cart', '', TRUE);
$this->load->view('layout/default', $data);
}
VIEW:
<?php if(is_array($list)): ?>
<?php foreach($list as $row):?>
<tr>
<td><?=$row->name?></td>
</tr>
<?php endforeach ?>
<?php endif;?>
but i have this following error:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: shop/cart.php
Line Number: 18
anyhelp guys? :(
I see you are using Code igniter (nice!)
I would do the following to ensure the $key is taking 'name'
public function index() {
foreach ($_SESSION['cartProducts'] as $key => $value) {
echo $key;
} }
Then
public function index() {
$in_cart = array();
if (!isset($_SESSION['cartProducts'])){
$in_cart['list'] = "No Products";
}
else{
foreach ($_SESSION['cartProducts'] as $key => $value) {
$in_cart[$key] = $this->shopmod->get_one_data($key);
}
}
$this->load->vars($cart);
$data['cart'] = $this->load->view('shop/cart', '', TRUE);
$data['list'] = $in_cart;
$this->load->view('layout/default', $data); }
PHP is telling you exactly what is wrong.
You are trying to access the name property of the $row array when the -> syntax is specifically reserved for objects.
To access array values, you use square brackets and keys: <?=$row['name']?>
Helpful hint to understand - What you're doing is quasi-equivalent to: 7->name, insofar as the left value (7) has no idea how to use the arrow syntax. It's reserved for when the left value is an object. Not an integer, or in your case, an array.
Update after your comment:
You would get at the data like this:
<? foreach($row['list'] as $r):?>
<tr>
<td><?=$r[0]->name;?></td>
</tr>
<? endforeach;?>

I have a question about using form_dropdown()

I have a question about using form_dropdown().
table:category
cat_id
cat_name
Controller:
function index()
{
$this->load->model('category_model');
$data['category'] = $this->category_model->cat_getallcat();
$this->load->view('category_input',$data);
}
Model:category_model
function cat_getallcat()
{
$this->load->database();
return $this->db->get('category')->result();
}
View:
<?php
$this->load->helper('form');
echo form_open('send');
$list[''] = 'Please select a Category';
foreach($query as $row)
{
$list[$row->cat_id] = ucfirst(htmlspecialchars($row->cat_name));
}
echo form_dropdown('category', $list);
echo form_close();
?>
error obtained:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/category_input.php
Line Number: 28
the ->result() will return the first row only, so this function is what you want to loop over.
Model
function cat_getallcat()
{
$this->load->database();
return $this->db->get('category');
}
View
foreach($query->result() as $row)
{
$list[$row->cat_id] = ucfirst(htmlspecialchars($row->cat_name));
}
EDIT:
Also, you are sending the result as $data['category'] then trying to access it as $query. So really the foreach would be foreach($category->result() as $row) in this example
You are asking foreach to loop over $query, but I you haven't set $query as a variable anywhere that I can see.
Since you set $data['category'] to hold your query result() in your controller, you need to loop over $category in the view:
foreach($category as $row)
{
$list[$row->cat_id] = ucfirst(htmlspecialchars($row->cat_name));
}

Resources