Undefined property PHP error on Codeigniter - php

I am super stuck on a problem. I went through many solution give here related to this but I did not found any solution to my error.
this is the error message I am facing and I used print_r to view what is the output but is also a dead end.
My controller - Search.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Search extends CI_Controller {
function index(){
$this->load->model("ModSearch");
$data["get_ztable"] = $this->ModSearch->get_zscore();
$data["get_course"] = $this->ModSearch->getCourse();
$data["get_stream"] = $this->ModSearch->getStream();
$data["get_district"] = $this->ModSearch->getDistrict();
$data["get_uni"] = $this->ModSearch->getUniversity();
$this->load->view('addZscore',$data);
}
Model - ModSearch.php
public function get_zscore(){
$query = $this->db->get('tbl_zscore');
return $query;
}
View - addZscore.php
<table style="width:50%">
<tr>
<th>Z ID</th>
<th>Z Score</th>
</tr>
<?php echo print_r($get_ztable);?>
<?php
if($get_ztable->num_rows() > 0)
{
foreach ($get_ztable as $row)
{
?>
<tr>
<td><?php echo $row->z_id; ?></td>
<td><?php echo $row->z_score; ?></td>
</tr>
<?php
}
}else{
echo 'Database Error(' . $this->db->_error_number() . ') - ' . $this->db->_error_message();
}
?>
</table>

You have to make changes in your model function that must return a "result" that you can easily use in your view. So just replace
return $query
with
return $query->result()
Or make a change in your foreach loop in views from
foreach($get_ztable as $row)
to
foreach($get_ztable->result() as $row)

Related

Undefined variable,index error fetching data codeigniter

Im fetching data from a table to another table that will be shown in my dashboard page for a user after loggin in.
But there is a problem with the indexes, i got this error:
Here is the line error:
Here is my code:
My view file ("usuario"):
<thead>
<th>id</th>
<th>User</th>
<th>Subject</th>
<th>Grade</th>
<th>Date</th>
</thead>
<tbody>
<?php
if (count($records) > 0 && $records != false) {
foreach($records as $record) {
echo "<tr>
<td>".$record['id']."</td>
<td>".$record['User']."</td>
<td>".$record['name']."</td>
<td>".$record['grade']."</td>
<td>".$record['date']."</td>
</tr>";
}
}
?>
</tbody>
</body>
</html>
My controller file ("login"):
public function home(){
$data['record']=$this->m_login->getDetails();
$this->load->view('usuario',$data);
}
My model file ("m_login"):
public function getDetails()
{
$st=$this->db->SELECT('cursadas.*, usuarios.name as usuarios, materias.name as materias_name')->from('cursadas')
->join('usuarios','usuarios.id=cursadas.user_id')
->join('materias','materias.id=cursadas.subject_id')
->WHERE('cursadas.user_id=',$this->session->userdata['id'])
->get()->result_array();
return $st[0];
}
You have the variable $records on view but not on controller
Change
$data['record'] = $this->m_login->getDetails();
To
// add this array() just in case no results found
$data['records'] = array();
$data['records'] = $this->m_login->getDetails();
$this->load->view('usuario', $data);
Another way is on controller
$results = $this->m_login->getDetails();
$data['records'] = array();
if ($results) {
foreach ($results as $result) {
$data['records'][] = array(
'id' => $result['id'],
'User' => $result['User'],
'name' => $result['name'],
'grade' => $result['grade'],
'date' => $result['date']
);
}
}
$this->load->view('usuario',$data);
View
<?php if ($records) {?>
<?php foreach($records as $record) {?>
<tr>
<td><?php echo $record['id'];?></td>
<td><?php echo $record['User'];?></td>
<td><?php echo $record['name'];?></td>
<td><?php echo $record['grade'];?></td>
<td><?php echo $record['date'];?></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td>No Results Found</td>
</tr>
<?php } ?>
Wrong array index in your controller.
Change this
$data['record']=$this->m_login->getDetails();
to
$data['records']=$this->m_login->getDetails();
result_array() return returns result with array so you need to it like this -
if (count($record) > 0 && $record != false) {
foreach($record as $rec){
echo "<tr>
<td>".$rec['id']."</td>
<td>".$rec['User']."</td>
<td>".$rec['name']."</td>
<td>".$rec['grade']."</td>
<td>".$rec['date']."</td>
</tr>";
}
}
Please check this from above code and comment if you have any problem

Data not shown in view Codeigniter

I am new in Codeigniter and i have problem when trying to display data in view page. I have follow Codeigniter documentation, tutorials and questions in stackoverflow but still no answer can help me althought i run the tutorial and it work perfectly. but when i implement in my code, it give me an error. Hope you guys can help me. I am not sure what the problem. Thank you in advanced.
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: b
Filename: home/adminviewbranch.php
Line Number: 81
Form.php(controller)
public function view_branch(){
$this->load->model('branch_model');
$data = array();
$data['b'] = $this->branch_model->branch_view();
$this->load->view('home/adminviewbranch', $data);
}
branch_model.php(model)
public function branch_view(){
//data is retrive from this query
$query = $this->db->get('branch');
return $query;
}
adminviewbranch.php(view)
<div id="page" class="container">
<table id="table_id" class="display">
<thead>
<tr>
<th>Branch Name</th>
<th>Branch Address</th>
<th>Branch Contact</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
if(count($b)>0) {
foreach ($b as $row) {
?>
<tr>
<td><?=$row->branch_name;?></td>
<td><?=$row->branch_add;?></td>
<td><?=$row->branch_Hp;?></td>
<td><?=$row->branch_Hp;?></td>
<?php
}
}
else {
echo "No Record found!";
}
?>
</tr>
</tbody>
</table>
</div>
in foreach do foreach ($b->result() as $row)
I think there is missing function in your foreach.
Try this:
<?php
if(count($b)>0)
{
foreach ($b->result() as $row){
?>
Modify your model code like below
public function branch_view(){
//data is retrive from this query
$query = $this->db->get('branch')->result_array();
return $query;
}
Change your model code to following
public function branch_view(){
//data is retrive from this query
$query = $this->db->get('branch');
return $query->result_array(); // this allows you to fetch results in the form of multidimentional array
}
Then you can access it in view as
<?php
if(count($b)>0)
{
foreach ($b as $row)
{
?>
<tr>
<td><?=$row['branch_name'];?></td>
<td><?=$row['branch_add'];?></td>
<td><?=$row['branch_Hp'];?></td>
<td>Action</td>
</tr>
<?php
}
}
else
{
echo "<tr colspan='3'><td>No Record found!</td></tr>";
}
?>
in model change this line
$query = $this->db->get('branch');
to
$query = $this->db->get('branch')->result();
(OR)
in view change this lines
<?php
if(count($b)>0) {
foreach ($b as $row) {
?>
to
<?php
if($b->num_rows()>0) {
foreach ($b->result() as $row) {
?>
Your model is not result anything.you can check with print_r() function.you must use be returning with object or array.return $query->result();
and your view must be foreach($tes as $t){$t->your_view}
or return $query->row();
with single data $row->your_view

How to convert php script to codeigniter MVC?

I have PHP script and work:
<?php
$con=mysqli_connect("localhost","root","","dbm");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result3 = mysqli_query($con,"select t.tgl_transaksi, p.kode_produk, tp.hp_tujuan, d.nama as nama2, sr.ket as ket2 from dbm.transaksi_psa tp
left join dbm.transaksi t
on tp.id_transaksi=t.id_transaksi
left join dbm.produk p
on tp.kode_produk = p.kode_produk
left join dbm.set_report sr on t.status=sr.jenis
left join dbm.distributor d on (tp.id_distributor=d.id_distributor and tp.com=d.com)
where date(t.tgl_transaksi)=date(now())
order by t.tgl_transaksi DESC");
echo "
<div class='table-responsive'>
<table class='table table-hover' id='t01'>
<tr>
<th>Tanggal</th>
<th>Produk</th>
<th>Tujuan</th>
<th>Suplier</th>
<th>Status</th>
</tr>";
while ($row = mysqli_fetch_array($result3))
{
echo "<tr>";
echo "<td>" . $row['tgl_transaksi'] . "</td>";
echo "<td>" . $row['kode_produk'] . "</td>";
echo "<td>" . $row['hp_tujuan'] . "</td>";
echo "<td>" . $row['nama2'] . "</td>";
echo "<td>" . $row['ket2'] . "</td>";
echo "</tr>";
}
echo "</table></div> <br><br><br>";
mysqli_close($con);
?>
And I try change to Codeigniter MVC - OOP:
Models:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ikhtisar_model extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//read the ikhtisar list from db
public function get_all()
{
$this->db->select('t.tgl_transaksi AS tgl, p.kode_produk AS kode, tp.hp_tujuan AS nohp, d.nama AS nama2, sr.ket AS ket2', FALSE)
->from('transaksi_pulsa tp')
//$this->db->where('date(t.tgl_transaksi)', 'date(now())');
->join('transaksi t','tp.id_transaksi=t.id_transaksi', 'left')
->join('produk p','tp.kode_produk = p.kode_produk', 'left')
->join('set_report sr','t.status=sr.jenis', 'left')
->join('distributor d','tp.id_distributor=d.id_distributor and tp.com=d.com', 'left')
->order_by("t.tgl_transaksi", "DESC");
$ikhtisar = $this->db->get();
//->result_array();
//return $ikhtisar;
}
}
Controllers:
<?php
if ( ! defined('BASEPATH')) exit('Akses di blok. Cek kembali link yang Anda tuju!');
class ikhtisar extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
}
public function index()
{
//load the ikhtisar_model
$this->load->model('ikhtisar_model');
//call the model function to get the ikhtisar data
$ikhresult = $this->ikhtisar_model->get_all();
$data['ikhlist'] = $ikhresult;
//load the ikhtisar_view
$this->load->view('templates/header', $data);
$this->load->view('ikhtisar_view',$data);
$this->load->view('templates/footer', $data);
}
}
Views:
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<div class="page-content">
<div class="row">
<div class="col-md-12 col-sm-12">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Tanggal</th>
<th>Produk</th>
<th>Tujuan</th>
<th>Suplier</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<? foreach($ikhtisar->result_array() as $ikh): ?>
<tr>
<td><?=$ikhlist['tgl']?></td>
<td><?=$ikhlist['kode']?></td>
<td><?=$ikhlist['nohp']?></td>
<td><?=$ikhlist['nama2']?></td>
<td><?=$ikhlist['ket2']?></td>
</tr>
<? endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
But, what I get, the data doesn't display at all. The header, the footer, display correctly.
First you have to return data from your model
class Ikhtisar_model extends CI_Model{
public function get_all()
{
.........................
$ikhtisar = $this->db->get();
return $ikhtisar;
}
}
second you have to pass data to your view from contorller. You already did it.
public function index()
{
//load the ikhtisar_model
$this->load->model('ikhtisar_model');
//call the model function to get the ikhtisar data
$ikhresult = $this->ikhtisar_model->get_all();
$data['ikhlist'] = $ikhresult;//you got it and you will get your variable as $ikhlist at your view
//load the ikhtisar_view
$this->load->view('templates/header', $data);
$this->load->view('ikhtisar_view',$data);
$this->load->view('templates/footer', $data);
}
Now display at your view.You wrote foreach loop worng.It should be like this
<? foreach($ikhlist->result_array() as $ikh): ?>
<tr>
<td><?=$ikh['tgl']?></td>
<td><?=$ikh['kode']?></td>
<td><?=$ikh['nohp']?></td>
<td><?=$ikh['nama2']?></td>
<td><?=$ikh['ket2']?></td>
</tr>
<? endforeach; ?>
better use full php tag instead of short tag.like this
<?php instead of <?
and
<?php echo instead <?=
Thanks for helping me, Mr. Shaiful Islam. All I get, this error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: ikhtisar
Filename: ikhtisar/ikhtisar_view.php
Line Number: 19
Tanggal Kode No HP Nama2 Ket2
( ! ) Fatal error: Call to a member function result_array() on a non-object in /var/www/html/cinew/application/views/ikhtisar/ikhtisar_view.php on line 19
Call Stack
# Time Memory Function Location
1 0.0001 131424 {main}( ) ../index.php:0
2 0.0003 132712 require_once( '/var/www/html/cinew/system/core/CodeIgniter.php' ) ../index.php:202
3 0.0063 340720 call_user_func_array ( ) ../CodeIgniter.php:359
4 0.0063 340852 ikhtisar->index( ) ../CodeIgniter.php:359
5 0.3295 372728 CI_Loader->view( ) ../ikhtisar.php:20
6 0.3295 373004 CI_Loader->_ci_load( ) ../Loader.php:419
7 0.3296 390908 include( '/var/www/html/cinew/application/views/ikhtisar/ikhtisar_view.php' ) ../Loader.php:833
Line 19 on the file:
<?php foreach($ikhtisar->result_array() as $ikh): ?>
PS: I'm sorry for using "Post Your Answer". This is not my solution answer for my own problem really. I can't use code in the comment.

Codeigniter: foreach method or result array?? [Models +View]

I am currently following tutorials on viewing data from the database using the Framework Codeigniter. There are various ways in which I've learnt. Is there is a more realiable way- either displaying as an array or using 'foreach' in the view file? Any opinions would be helpful.
This is my code using the two methods:
Method 1 Model:
function getArticle(){
$this->db->select('*');
$this->db->from('test');
$this->db->where('author','David');
$this->db->order_by('id', 'DESC');
$query=$this->db->get();
if($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}$query->free_result();
}
}
Method 1 View file:
<?php foreach($article as $row){ ?>
<h3><?php echo $row->title; ?></h3>
<p><?php echo $row->content; ?></p>
<p><?php echo $row->author; ?></p>
<p><?php echo $row->date; ?></p>
<?php } ?>
Method 2 Model:
class News_model extends CI_Model {
function getArticle(){
$this->db->select('*');
$this->db->from('test');
$this->db->where('author', 'David');
$this->db->order_by('id', 'DESC');
$query=$this->db->get();
if ($query->num_rows()>0) {
return $query->row_array();
}
$query->free_result();
}
Method 2 View file:
<?php echo '<h3>' .$article['title'].'</h3>' ?>
<?php echo '<p>' .$article['content']. '</p>' ?>
<?php echo '<p>' .$article['author']. '</p>' ?>
<?php echo '<p>'. $article['date']. '</p>' ?>
I would do it like that:
Model
function getArticle() {
$this->db->select('*');
$this->db->from('test');
$this->db->where('author','David');
$this->db->order_by('id', 'DESC');
return $this->db->get()->result();
}
}
Controller
function get_tests() {
$data = array(
'tests' => $this->mymodel->getArticle()
}
$this->load->view('myview', $data);
}
View
<table>
<?php foreach($tests as $test) { ?>
<tr>
<td><?php echo $test->title;?></td>
<td><?php echo $test->content;?></td>
<td><?php echo $test->author;?></td>
<td><?php echo $test->date;?></td>
</tr>
</table>
If you wish to work with arrays rather than objects, in your model change line
return $this->db->get()->result();
to
return $this->db->get()->result_array();
and in views echo like
<td><?php echo $test['title'];?></td>
P.S.
In your code you use $query->free_result(); but it doesn't even run because when you use keyword return everything after that is not even parsed. It's not necessary to free results anyway.
P.S.2.
You use if($query->num_rows() > 0) { but don't have the else part, it means that it's not necessary too. If you'll return no lines to your foreach statement in the view, you won't get any errors.

Codeigniter 2 not returning from model as object only as result array

So, i've been using codeigniter for a while and I've never had an issue running a query in my model and returning it to my controller which then passes it into my view where I access it as an object, like so:
MODEL (somemodel)
function getdata()
{
$query = $this->db->get('sometable');
return $query;
}
CONTROLLER (somecontroller)
function controldata()
{
$this->load->model('somemodel');
$data['dbdata'] = $this->somemodel->getdata();
$this->load->view('someview',$data);
}
VIEW (someview)
<?php
foreach($dbdata->result() as $row) {
echo $row->id;
echo $row->name;
echo $row->whatever;
echo "<br />";
}
?>
But now for whatever reason in 2.0 it's making use $dbdata->result_array() as $row instead.
Basically it's returning the results as an array instead.
It doesn't make any sense, has something changed in the new version?
Thanks,
So here's my code:
MODEL (admin_model)
function show_allproducts($sort,$order,$limit,$offset)
{
$this->db->select('products.id,productcategories.categoryname,products.name,products.internetspecial,products.added,products.modified');
$this->db->from('products');
$this->db->join('productcategories','products.productcategories_id = productcategories.id');
$this->db->order_by($sort,$order);
$this->db->limit($limit,$offset);
$query = $this->db->get();
if($query->num_rows() > 0)
{
return $query;
}
else
{
return FALSE;
}
}
CONTROLLER (admin)
function show_allproducts()
{
$data['title'] = 'All Products';
$this->load->library('pagination');
$config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/admin/show_allproducts';
$config['total_rows'] = $this->db->get('products')->num_rows();
$config['per_page'] = 10;
$config['num_links'] = 5;
$config['full_tag_open'] = '<div class="paggination right">';
$config['full_tag_close'] = '</div>';
$config['prev_link'] = '< prev';
$config['next_link'] = 'next >';
$config['cur_tag_open'] = '<a class="active">';
$config['cur_tag_close'] = '</a>';
$this->pagination->initialize($config);
$this->load->model('admin_model');
$data['tabledata'] = $this->admin_model->show_allproducts('name','ASC',$config['per_page'],$this->uri->segment(3));
$data['nav'] = 'admin/pagesections/nav';
$data['maincontent'] = 'admin/pages/show_allproducts';
$this->load->view('admin/template',$data);
}
VIEW (show_all_products)
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<?php if($tabledata) { ?>
<tr>
<th>ID</th>
<th>CATEGORY</th>
<th>NAME</th>
<th>ADDED</th>
</tr>
<?php foreach($tabledata->result() as $row) { ?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->categoryname; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->added;) ?></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td>NO DATA</td>
</tr>
<?php } ?>
</table>
Unless you specify $dbdata->result_array() as $row , It wont return the results as array. The same code which you've posted must be working in CI 2.0.
If not, may be the problem with $this->db->get('sometable').
Try with $this->db->query('select * from sometable'). But as far as i know, both are same...
Ok folks, no lie, I found the freaking problem.
Looking at the fourth td where $row->added; is at, there's a close parantheses at the end of it that was causing 4 days of mayhem.
Kindest regards to all those who tried to help. Sometimes it doesn't matter how many eyes are on it I guess.

Categories