Reputation: 59
Please help me in this...I am learning CodeIgniter and i got stuck on this error.There must be some silly mistake. I am using xampp software for this. It keeps popping undefined variable rows.
table name is 'user' view file name is try model file name is trydb controller file name is condb
ERROR
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: rows
Filename: views/try.php
Line Number: 12
Backtrace:
File: C:\xampp\htdocs\ciagain\application\views\try.php
Line: 12
Function: _error_handler
File: C:\xampp\htdocs\ciagain\application\controllers\Welcome.php
Line: 27
Function: view
File: C:\xampp\htdocs\ciagain\index.php
Line: 292
Function: require_once
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/try.php
Line Number: 12
Backtrace:
File: C:\xampp\htdocs\ciagain\application\views\try.php
Line: 12
Function: _error_handler
File: C:\xampp\htdocs\ciagain\application\controllers\Welcome.php
Line: 27
Function: view
File: C:\xampp\htdocs\ciagain\index.php
Line: 292
Function: require_once
View File
<title>
Connecting data base
</title>
</head>
<body>
<?php
foreach($rows as $r){
echo $r->ID;
echo $r->Name;
}
?>
</body>
</html>
Modal File
<?php
class Site_model extends Model {
function getAll() {
$q = $this->db->get('user');
if($q->num_rows()>0) {
foreach ($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
}
?>
Controller file
<?php
class Site extends CI_Controller {
function index() {
$this->load->model('trydb');
$data['rows'] = $this->trydb->getAll();
$this->load->view('try', $data);
}
}
?>
Default controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->view('welcome_message');
}
public function tryagain(){
$this->load->view('try');
}
}
Upvotes: 1
Views: 4387
Reputation: 2562
Delete space between } and ?> on line 12. It will help. Also there is no Codeigniter 4 :)
Upvotes: 0
Reputation: 123
Why has you put foreach loop in model? you can use this:
function getAll() {
$q = $this->db->get('user');
$data = $q->result();
return $data;
}
and as suggested by DS9 , use below in view files.
if(isset($rows) && sizeof($rows)>0)
{
foreach($rows as $r)
{
}
}
Upvotes: 2
Reputation: 3033
It is not error
, it is a notice
Severity: Notice
To resolve this you can defined the variable or disable the notice. Prefer first one.
like,
if(sizeof($rows)>0)
{
foreach($rows as $r){
}
}
Upvotes: 1