[英]Undefined variable in CodeIgniter 3
请帮助我...我正在学习CodeIgniter,我遇到了这个错误。必定会有一些愚蠢的错误。 我正在使用xampp软件。 它不断弹出未定义的变量行。
表名是'用户'视图文件名是try模型文件名是trydb控制器文件名是condb
错误
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
查看文件
<title>
Connecting data base
</title>
</head>
<body>
<?php
foreach($rows as $r){
echo $r->ID;
echo $r->Name;
}
?>
</body>
</html>
模态文件
<?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;
}
}
}
?>
控制器文件
<?php
class Site extends CI_Controller {
function index() {
$this->load->model('trydb');
$data['rows'] = $this->trydb->getAll();
$this->load->view('try', $data);
}
}
?>
默认控制器
<?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');
}
}
为什么你把foreach循环放在模型中? 你可以用这个:
function getAll() {
$q = $this->db->get('user');
$data = $q->result();
return $data;
}
并且根据DS9的建议,在视图文件中使用以下内容。
if(isset($rows) && sizeof($rows)>0)
{
foreach($rows as $r)
{
}
}
这不是error
,而是一个通知
严重性:注意
要解决此问题,您可以定义变量或禁用通知。 首先选择一个。
喜欢,
if(sizeof($rows)>0)
{
foreach($rows as $r){
}
}
删除第12行上}和?>之间的空格。这会有所帮助。 还有没有Codeigniter 4 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.