Error trying to fetch data using codeigniter - php

I got 3 tables; my tables are "cursadas","usuarios" and "materias"
"cursadas" includes:(id, user_id[is the foreign key to the column "id" of the table "usuarios"], subject_id[is the foreign key to the column "id" of the table "materias"], grade, date)
"usuarios" includes:(id,username,name,lastname,password,type,status,date)
"materias" includes:(id, career_id, name, description, hours)
This is my final table "cursadas"(with data from tables "materias" and "usuarios")
TAKE A LOOK, i need something like this:
I got this error:
I think there is an error with my query, i do not know what should i do to make this work :S
Here is my code:
My view file ("usuario"):
<input id="busqueda_tabla" type="text">
<table class="table table-hover" align="center" border="1" cellspacing="0" cellpadding="0" width="700" id="tabla_busqueda">
<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"):
<?php
Class Login extends CI_Controller{
public function index(){
$this->load->view('login_form');
}
public function do_login()
{
// load the form_validation library
$this->load->library('form_validation');
$this->form_validation->set_rules('usuario', 'Username', 'trim|required|min_length[3]|alpha_numeric');
$this->form_validation->set_rules('contrasena', 'Password', 'trim|required|min_length[6]');
// if there is errors
if ($this->form_validation->run() == FALSE) {
// this will load your form with the errors
$this->load->view('login_form');
} else {
// if no errors we will hit the database
$user=$this->input->post('usuario', true);
$pass=$this->input->post('contrasena', true);
$cek = $this->m_login->proceso_login($user,$pass);
$hasil=count($cek);
if($hasil > 0)
{
$pelogin =$this->db->get_where('usuarios',array('username' => $user, 'password' => $pass))->row();
// here $pelogin has the id of the user
// create session like this
$this->session->set_userdata(array('id' => $pelogin->id));
if($pelogin ->type == 0)
{
// here goes the admin data
redirect('login/admin');
}
else{
//call here usuario method which has user data who logged in like
redirect('login/usuario');
// OR
// Call some method which has user data in $records and
}
}
redirect('login/index');
}
}
public function admin (){
$data['records']=$this->m_login->getDetails();
$this->load->view('admin',$data);
}
public function usuario(){
$data['records']=$this->m_login->getDetails();
$this->load->view('usuario',$data);
}
And the model file("m_login")- with the query!
<?php
class m_login extends CI_Model{
public function proceso_login($user,$pass){
$this->db->where('username', $user);
$this->db->where('password', $pass);
return $this->db->get('usuarios')->row();
}
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];
}
}
?>

Change the query :
$st = $this->db->SELECT('cursadas.date as date, cursadas.grade as grade, usuarios.username as user, materias.name as subject')->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;
And pls check the database field type use datetime for date int for id and so as required
In the view :
<tbody>
<?php
if (count($records) > 0 && $records != false) {
$id = 1;
foreach($records as $record) {
echo "<tr>
<td>".$id."</td>
<td>".$record['user']."</td>
<td>".$record['subject']."</td>
<td>".$record['grade']."</td>
<td>".$record['date']."</td>
</tr>";
$id++;
}
}
?>

Related

Laravel One to Many Relationship not working

I am doing my assignment for a hotel booking system. I have a table named bookings and another table room. I did a one to many relations between them I want to return the room name to the home view but it is always showing Trying to get property of non-object. This is my code.
BOOKING Controllerclass GuestBookingController extends Controller
public function new()
{
$rooms = Room::all();
$guests = Guest::all();
return view('guestbookings.new', compact('rooms','guests'));
}
public function store(Request $request)
{
$validatedData = $request->validate([
'checkin_dtime' => 'required',
'checkout_dtime' => 'required',
'id_number' => 'required|unique:guests',
'mobile' => 'required',
]);
$result = Booking::where('checkin_dtime', '<=',$request->checkin_dtime)->where('checkout_dtime', '>=',$request->checkout_dtime)->where('room_id',$request->room_id)->first();
if(!$result){
$bookings = new Booking;
$bookings->checkin_dtime = $request->input('checkin_dtime');
$bookings->checkout_dtime = $request->input('checkout_dtime');
$bookings->user_id = auth()->user()->id;
$bookings->save();
$guests = new Guest;
$guests->id_number = $request->input('id_number');
$guests->mobile = $request->input('mobile');
$guests->save;
}
return redirect('home');
Home view
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>Room Name</td>
<td>Check-In</td>
<td>Check-Out</td>
<td>Status</td>
<td>Action</td>
</tr>
</thead>
<tbody>
#foreach($bookings as $booking)
<tr>
<td>{{$booking['id']}}</td>
<td>{{$booking->room->room_name}}</td>
<td>{{$booking['checkin_dtime']}}</td>
<td>{{$booking['checkout_dtime']}}</td>
<td>
Booking Model
public function room()
{
return $this->belongsTo(Room::class, 'room_id');
}
public function user(){
return $this->belongsTo(User::class);
}
this is your controller code as per the question:
$bookings = new Booking;
$bookings->checkin_dtime = $request->input('checkin_dtime');
$bookings->checkout_dtime = $request->input('checkout_dtime');
$bookings->user_id = auth()->user()->id;
$bookings->save();
you are not adding any room_id column. that means your room_id is null at database. so when you are trying to call relationship, eloquent is unable to build the relationship and you are getting the error. your code should be:
$bookings = new Booking;
$bookings->checkin_dtime = $request->input('checkin_dtime');
$bookings->checkout_dtime = $request->input('checkout_dtime');
$bookings->room_id = $request->input('room_id');
$bookings->user_id = auth()->user()->id;
$bookings->save();

No data available in table (Codeigniter)

I fetched data from my localhost database. However, a "No data available in table" shows up in my datatables. I am having a hard time figuring out what is the problem because I don't get any errors from it. I use the function fetch in my system_model.php to fetch data from the database. Is there any way to find why values from the database are not showing?
Here is my code for my controller:
class SFM_controller extends CI_Controller {
public function __construct() {
parent::__construct();
// Load form helper library
$this->load->helper('form');
$this->load->helper('url');
// // Load form validation library
$this->load->library('form_validation');
// // Load session library
$this->load->library('session');
// Load database
$this->load->model('system_model');
}
public function index()
{
$data = array(
//'logo' => base_url()."/assets/images/logo/fams-small.png",
//'full_name' => $this->session->user_full_name,
'fo_supp' => $this->system_model->fetch('fo_supp'),
);
$this->load->view('includes/SFM/SFM_Header');
$this->load->view('includes/SFM/SFM_NavBar');
$this->load->view('SFM_view', $data);
$this->load->view('includes/SFM/SFM_Footer');
}
function logout()
{
$this->load->view('includes/Login/Login_Header'); //$data);
$this->load->view('Login_view');
$this->load->view('includes/Login/Login_Footer');
}
}
Here is my code for my Model:
class system_model extends CI_Model
{
function fetch($table, $where = null, $group_by = null, $order_by = null, $limit = null)
{
if($where != null) {
$this->db->where($where);
}
if($group_by != null) {
$this->db->group_by($group_by);
}
if($order_by != null) {
foreach ($order_by as $key => $value) {
$this->db->order_by($key, $value);
}
}
if($limit != null) {
$this->db->limit($limit);
}
$query = $this->db->get($table);
return $query->num_rows() > 0 ? $query->result() : false;
}
Here is my code for my View:
<table id="datatable-buttons" class="table table-striped table-bordered">
<thead>
<tr>
<th>Supplier Code</th>
<th>Address</th>
<th>Country</th>
<th>Description</th>
<th>Telephone Number</th>
<th>Fax Number</th>
<th>Consolidating Agent</th>
<th>Contact Person</th>
<th>Actions</th>
<th>Discount 1</th>
<th>Discount 2</th>
<th>Discount 3</th>
<th>Discount 4</th>
<th>Discount 5</th>
<th>Last Transaction</th>
<th>Old Supplier</th>
</tr>
</thead>
<tbody>
<?php if(!empty($fo_supp)): ?>
<?php foreach($fo_supp as $supp): ?>
<tr>
<td> <?=$supp->supp_code?> </td>
<td> <?=$supp->address." ".$supp->address2?></td>
<td><?=$supp->country?></td>
<td><?=$supp->description?></td>
<td><?=$supp->tel_no?></td>
<td><?=$supp->fax_no?></td>
<td><?=$supp->contact?></td>
<td><?=$supp->cons_agent?></td>
<td>$320,800</td>
<td><?=$supp->disc1?></td>
<td><?=$supp->disc2?></td>
<td><?=$supp->disc3?></td>
<td><?=$supp->disc4?></td>
<td><?=$supp->disc5?></td>
<td><?=$supp->last_trans?></td>
<td><?=$supp->supp_code2?></td>
</tr>
<?php endforeach;?>
<?php endif; ?>
</tbody>
</table>
Var dump
Why is my var dump like this? and not showing values
Pass your $data array in the view file instead of header file in controller index function.
$this->load->view('SFM_view', $data);
SOLVED!
I was passing the data to the wrong controller in which my login submit is located in another controller!

Sorting a list alphabetically by clicking a link using CodeIgniter

I am pulling information from a database and displaying it on my page. I want to sort the data from one of the database table alphabetically by clicking on a link. I was able to achieve this using pure PHP but unable to do so with CodeIgniter because of the MVC structure. Using pure PHP the code was like:
<?php
if(isset($_GET['let']))
$let = $_GET['let'];
else
$let = '';
$query = "SELECT supplier, contact, telephone, email FROM suppliers WHERE supplier LIKE '$let%'";
// other codes
And a separate sort.php with the code:
All |
A |
B
This is how my page looks like:
Here is what my model looks like by tring to use a function called getSort()
class Supplier_model extends CI_Model
{
public function __construct()
{
/* Call the Model constructor */
parent::__construct();
}
function getCity()
{
$query = $this->db->query('SELECT cityidd,city FROM citys');
return $query->result_array();
}
function getPaymentMode()
{
$query = $this->db->query('SELECT id,paymentmode FROM paymentmodes');
return $query->result_array();
}
function getBank()
{
$query = $this->db->query('SELECT id,bankname FROM banks');
return $query->result_array();
}
function getCategories()
{
$query = $this->db->query('SELECT id,supplycategory FROM supplycategories');
return $query->result_array();
}
function getStaff()
{
$query = $this->db->query('SELECT firstname,lastname FROM employees');
return $query->result_array();
}
function getBankBranch($bank_id)
{
$query = $this->db->query('SELECT id,bankbranch FROM bankbranches WHERE bank='.$bank_id);
return $query->result_array();
}
function getPosts()
{
$this->db->select("supplier,contact,telephone,email");
$this->db->from('suppliers');
$this->db->order_by("supplier", "asc");
$query = $this->db->get();
return $query->result();
}
function getSort()
{
$query = $this->db
->select('supplier,contact,telephone,email')
->from('suppliers')
->where('supplier')
->like('supplier', 'let', 'after')
->get();
return $query->result();
}
function addSupplier()
{
$this->load->database();
$supplier = $this->input->post('supplier');
$taxpin = $this->input->post('taxpin');
$contact = $this->input->post('contact');
$addresss = $this->input->post('addresss');
$citys = $this->input->post('citys');
$telephone = $this->input->post('telephone');
$email = $this->input->post('email');
$website = $this->input->post('website');
$paymentmodes = $this->input->post('paymentmodes');
$kesaccount = $this->input->post('kesaccount');
$usdaccount = $this->input->post('usdaccount');
$banks = $this->input->post('banks');
$bankbranches = $this->input->post('bankbranches');
$bankcode = $this->input->post('bankcode');
$swiftcode = $this->input->post('swiftcode');
$mobilepaymentnumber = $this->input->post('mobilepaymentnumber');
$mobilepaymentname = $this->input->post('mobilepaymentname');
$chequeddressee = $this->input->post('chequeddressee');
$status = $this->input->post('status');
$categorysuppliers = $this->input->post('categorysuppliers');
$staff = $this->input->post('staff');
$data = array(
'supplier' => $supplier, 'taxpin' => $taxpin, 'contact' => $contact, 'addresss' => $addresss,
'citys' => $citys, 'telephone' => $telephone, 'email' => $email, 'website' => $website,
'paymentmodes' => $paymentmodes, 'kesaccount' => $kesaccount, 'usdaccount' => $usdaccount,
'banks' => $banks, 'bankbranches' => $bankbranches, 'bankcode' => $bankcode,
'swiftcode' => $swiftcode, 'mobilepaymentnumber' => $mobilepaymentnumber,
'chequeddressee' => $chequeddressee, 'status' => $status,
'categorysuppliers' => $categorysuppliers, 'staff' => $staff);
$this->db->insert('suppliers', $data);
}
}
This is how my controller looks like by using a function called sort_suppliers:
<?php
class Supplier extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url', 'form');
$this->load->model('supplier_model');
$this->load->database();
}
public function index()
{
$this->load->helper('form', 'html');
$data['cities'] = $this->supplier_model->getCity();
$data['modes'] = $this->supplier_model->getPaymentMode();
$data['banks'] = $this->supplier_model->getBank();
$data['categories'] = $this->supplier_model->getCategories();
$data['staffs'] = $this->supplier_model->getStaff();
$this->load->view('supplier_add', $data);
}
public function save()
{
$this->load->model('supplier_model');
if($this->input->post('submit'))
{
$this->supplier_model->addSupplier();
}
redirect('supplier/view_suppliers');
}
public function view_suppliers()
{
$this->load->helper('form');
$this->data['posts'] = $this->supplier_model->getPosts();
$this->load->view('suppliers_view', $this->data);
}
public function sort_suppliers()
{
$this->load->helper('form');
$this->data['sorts'] = $this->supplier_model->getSort();
$this->load->view('suppliers_view', $this->data);
}
public function get_branches()
{
$bank_id = $this->input->post('bank_id');
$bankbranch = $this->supplier_model->getBankBranch($bank_id);
foreach($bankbranch as $branch)
{
echo '<option value="'.$branch['id'].'">'.$branch['bankbranch'].'</option>';
}
}
}
I am so confused of how my view should look like because I am not even sure if my model and controller is right. I want when the user clicks on the href link ALL to get all the list from the database and when the user clicks on any alphabet letter the list from the database should only display the sorted list based on the letter clicked by the user. Here is my mixed up view:
<!DOCTYPE html>
<html>
<head>
<title>Supplier</title>
<style>
table {
border-collapse: separate;
border-spacing: 0;
}
th,
td {
padding: 10px 15px;
}
tbody tr:nth-child(even) {
background: #f0f0f2;
}a:link {
text-decoration: none;
}
</style>
</head>
<body>
<strong>Suppliers</strong><br><br>
Active |
Disabled <br><br>
All |
A |
B |
C |
D |
E |
F |
G |
H |
I |
J |
K |
L |
M |
N |
O |
P |
Q |
R |
S |
T |
U |
V |
W |
X |
Y |
Z |<br><br>
<hr>
<table>
<thead>
<tr>
<th align='left'>Supplier</th>
<th align='left'>Contact</th>
<th align='left'>Telephone</th>
<th align='left'>Email</th>
<th align='left'>LPO</th>
<th align='left'>Invoice</th>
<th align='left'>Profile</th>
</tr>
</thead>
<?php foreach($posts as $post)
{ ?>
<tr>
<td><?php echo $post->supplier; ?></td>
<td><?php echo $post->contact; ?></td>
<td><?php echo $post->telephone; ?></td>
<td><?php echo $post->email; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
Both your model and controller have the right idea though they could be a little more trick. This answer shows one possible approach.
Throughout this answer many functions shown in the question are not included because they don't affect the answer. There are a few of exceptions that are included because I want to comment on your code. (Sorry, can't help myself.)
First the controller.
Suppliers.php
class Suppliers extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url', 'form');
$this->load->model('supplier_model');
}
You have tendency to load things multiple times. CodeIgniter classes (helpers, libraries, models) are mostly "singletons". As such, if they are already loaded any attempt to load them again returns a reference to the previously loaded instance and does not create a new instance.
The first line in the next method has you loading a helper that's already loaded.
public function index()
{
//$this->load->helper('form', 'html'); 'form' helper already loaded in constructor
$this->load->helper('html');
$data['cities'] = $this->supplier_model->getCity();
$data['modes'] = $this->supplier_model->getPaymentMode();
$data['banks'] = $this->supplier_model->getBank();
$data['categories'] = $this->supplier_model->getCategories();
$data['staffs'] = $this->supplier_model->getStaff();
$this->load->view('supplier_add', $data);
}
The next function in the Suppliers class combines view_suppliers() and sort_suppliers() functions into one. Giving the function's parameter a default value allows it to be called without passing a value.
public function view($filter = "All")
{
if($filter === "All")
{
$filter = NULL;
}
$data['filter'] = $filter;
$data['suppliers'] = $this->supplier_model->get_suppliers($filter);
$this->load->view('suppliers_view', $data);
}
}
Using the procedural approach to creating links like this
A
won't work in the object oriented world of Codeigniter.
You cannot just link to a file, you have to link to a controller and possibly a function of that controller. CodeIgniter uses a segment-based approach to URLs. (Documentation)
example.com/controller/function/parameter
Directing a browser to example.com/suppliers will call suppliers->index() and example.com/suppliers/view calls suppliers->view().
You can pass a param to suppliers->view by using the "param" segment of the URI in the anchor tag, e.g. <a href='example.com/suppliers/view/K'> which would call suppliers->view("K").
Supplier_model.php
class Supplier_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
function getCity()
{
$query = $this->db->query('SELECT cityidd,city FROM citys');
return $query->result_array();
}
You never check if you actually get data back from the query which can bite you at times. But if you are not going to check if you got any rows you don't really need $query. The function could be simplified into this.
function getCity()
{
return $this->db->query('SELECT cityidd,city FROM citys')->result_array();
}
Getting the list of suppliers can be simplified into one function that will handle both sorted (a.k.a. filtered) and "All" records.
(Filtering and sorting database results are two different but related chores in my mind. I had to name the search variable $filter because I kept getting confused about what I was working on.)
This code illustrates one of the cool things about Query Builder - you don't have to run the various function in the order required for a valid SQL statement. Query Builder doesn't actual "build" the statement until get() is called so there is no problem with setting the like phrase before select or any other Query Builder method.
public function get_suppliers($filter)
{
if(isset($filter))
{
// $filter is not NULL
$this->db->like('supplier', $filter, 'after');
// Uncomment the next line of code and remove the other call
// to order_by if you only want filtered results sorted
//$this->db->order_by("supplier", "ASC");
}
$query = $this->db
->select("supplier,contact,telephone,email")
->from('suppliers')
// Remove (or comment) the next line of code
// if you do not want the suppliers in alphabetical order.
->order_by("supplier", "ASC")
->get();
return $query->num_rows() > 0 ? $query->result() : NULL;
}
If you're not familiar with PHP's ternary operator this line
return $query->num_rows() > 0 ? $query->result() : NULL;
does exactly the same thing as this if/else block.
if($query->num_rows() > 0)
{
return $query->result();
}
else
{
return NULL;
}
Which would you rather type?
(If you know what the ternary operator is I apologize for being pedantic.)
This next class function is included because I am once again being pedantic.
There is no point in assigning posted values to variables and then using those variables to set values in an array. Save a lot of typing and processing power by using $this->input->post while populating the $data array.
function addSupplier()
{
//$this->load->database(); do this in the constructor (or in autoload.php)
$data = array(
'supplier' => $this->input->post('supplier'),
'taxpin' => $this->input->post('taxpin'),
'contact' => $this->input->post('contact'),
'addresss' => $this->input->post('addresss'),
'citys' => $this->input->post('citys'),
'telephone' => $this->input->post('telephone'),
'email' => $this->input->post('email'),
'website' => $this->input->post('website'),
'paymentmodes' => $this->input->post('paymentmodes'),
'kesaccount' => $this->input->post('kesaccount'),
'usdaccount' => $this->input->post('usdaccount'),
'banks' => $this->input->post('banks'),
'bankbranches' => $this->input->post('bankbranches'),
'bankcode' => $this->input->post('bankcode'),
'swiftcode' => $this->input->post('swiftcode'),
'mobilepaymentnumber' => $this->input->post('mobilepaymentnumber'),
'mobilepaymentname' => $this->input->post('mobilepaymentname'),
'chequeddressee' => $this->input->post('chequeddressee'),
'status' => $this->input->post('status'),
'categorysuppliers' => $this->input->post('categorysuppliers'),
'staff' => $this->input->post('staff')
);
$this->db->insert('suppliers', $data);
}
}
Here's the <body> section of the view file modified to use the variables passed in the controller. A foreach loop makes building the filter links easy. Documentation on the anchor function HERE.
suppliers_view.php
<body>
<strong>Suppliers</strong><br><br>
<strong>Suppliers</strong><br><br>
<!-- These next two lines would cause the list to be suppliers that start with "Y". What do you really want? These links wouldn't work anyway. -->
<!-- Active |-->
<!-- Disabled <br><br>-->
<?php
$filter_values = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
echo anchor("suppliers/view", "All");
//make <a> tags for "A" through "Z"
foreach($filter_values as $value)
{
echo anchor("suppliers/view/{$value}", " | $value");
}
?>
<br><br>
<hr>
<table>
<thead>
<tr>
<th align='left'>Supplier</th>
<th align='left'>Contact</th>
<th align='left'>Telephone</th>
<th align='left'>Email</th>
<th align='left'>LPO</th>
<th align='left'>Invoice</th>
<th align='left'>Profile</th>
</tr>
</thead>
<?php
if(isset($suppliers)):
foreach($suppliers as $supplier):
?>
<tr>
<td><?= $supplier->supplier; ?></td>
<td><?= $supplier->contact; ?></td>
<td><?= $supplier->telephone; ?></td>
<td><?= $supplier->email; ?></td>
</tr>
<?php
endforeach;
else:
$msg = isset($filter) ? "No supplier names starting with the letter $filter." : "No Suppliers found.";
echo "<td>$msg</td>";
endif;
?>
</table>
</body>
Sorry for the long-winded answer. I hope it is helpful.

Codeigniter- admin add data for specific user and user see admin inputed data when he logged in

I've just completed user and admin signup and login system in codeigniter. I have two table massuser and meal. in the meal table admin add data for users and in the massuser table is recorded data when user sign up. and I am able to show specific user signup data into the view by session but I am not able to show admin inputed data in the same view. I have tried many times but I can't. please help me?
Meal Table structure
**================================
id---- username----meal---date
===============================**
Massuser Table structure
============================================================
id----fullname----username----password----email----regdate
============================================================
Controller
public function mymeals()
{
if($this->session->userdata('is_logged_in')){
$username = $this->session->userdata('username');
$data['results'] = $this->usermodel->get_meal($username);
$this->load->view('public/profile/profile',$data);
}else{
echo "No results";
}
}
model
public function get_meal($username)
{
$user = $this->session->userdata('username');
$this->db->select('*');
$this->db->from('meal');
$this->db->where('username', $user);
$query = $this->db->get()->result();
return $query;
}
view
<table class="table table-striped">
<tr>
<th>Date</th>
<th>Meal</th>
</tr>
<?php
foreach($results as $meal):?>
<tr>
<td><?php echo $meal->date;?></td>
<td><?php echo $meal->meal;?></td>
</tr>
<?php endforeach;?>
</table>
It could be that in your model you are accessing session data.
Do you still get the problem if you used the actual passed variable?
Try
public function get_meal($username) {
$this->db->select('*')
->from('meal')
->where('username', $username);
return $this->db->get()->result();
}

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!

Categories