我正在学习CodeIgniter来自此链接。我从数据库中获取数据时有点困惑。
<h2><?php echo $title; ?></h2>
<?php foreach ($news as $news_item): ?>
<h3><?php echo $news_item['title']; ?></h3>
<div class="main">
<?php echo $news_item['text']; ?>
</div>
<p><a href="<?php echo site_url('news/'.$news_item['slug']); ?>">View article</a></p>
在视图中显示数据时,他们在foreach循环中使用了变量$news
。但是,此变量永远不会在任何地方定义
答案 0 :(得分:1)
从here
复制$query = $this->db->get('mytable');
// Produces: SELECT * FROM mytable
The second and third parameters enable you to set a limit and offset clause:
$query = $this->db->get('mytable', 10, 20);
// Produces: SELECT * FROM mytable LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
You'll notice that the above function is assigned to a variable named $query, which can be used to show the results:
$query = $this->db->get('mytable');
foreach ($query->result_array() as $row)
{
echo $row['title'];
}
答案 1 :(得分:1)
尝试这样希望这会给你你想要的只是简单地创建一个控制器并在构造函数中调用相关的模型并执行你希望它返回数组的函数,这样你就可以在你的视图中获取并使用它。 控制器代码
class TestController extends Controller{
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->model('User');
}
public function index(){
$data['all_user']=$this->User->getAllUser();
$this->load->view('index',$data);
}
}
这是我的型号代码
class User extends CI_Model{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function getAllUser()
{
$this->db->select('*');
$this->db->from('users');
return $this->db->get()->result();
}
}
按照步骤操作 做一个控制器 在控制器内部创建一个功能 将相关的模型函数调用到它中,你肯定会得到结果。
答案 2 :(得分:0)
您是否看过这个Controller
代码? (在您选择的代码上方,在教程中)
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
$news
作为$data
元素从Controller
传递到View