问题
I'm learning kohana 3.3. I'm working on the model part. Basic query. But i don't know how to display the results i got from a query.
Here's the model.
APPPATH/classes/model/people.php
class Model_People extends Model {
public function show_data() {
$query = DB::query(Database::SELECT, 'SELECT * FROM people');
return $query;
}
}
APPPATH/classes/controller/people.php
class Controller_People extends Controller {
public function action_index() {
$model = Model::factory('people');
$view = View::factory('base_template');
$model->user = $model->show_data();
$this->response->body($view);
}
}
APPPATH/views/base_template.php
<?php
foreach($user as $row) {
echo "<h2>".$row['Name']."</h2>";
}
?>
I don't want to use ORM I'm using QUERY BUILDER. When I run the code it says variable user not defined. How do I display the results correctly? thanks.
回答1:
Try this
class Controller_People extends Controller {
public function action_index() {
$model = Model::factory('people');
$view = View::factory('base_template');
$view->user = $model->show_data();
$this->response->body($view);
}
}
then loop in view
<?php
foreach($user as $row) :
echo "<h2>".$row['Name']."</h2>";
endforeach;
?>
回答2:
Since you are learning Kohana, I would suggest using ORM, Kohana offers quite a powerful module for this.
After enabling the module you can use it like this
Model_People
class Model_People extends ORM {
}
Controller_People
public function action_index() {
$people = ORM::factory('People')->find_all();
$view = View::factory('base_template');
$view->people = $people;
$this->response->body($view);
}
base_template
<?php foreach ($people as $person) : ?>
<h2><?php echo $person->Name; ?></h2>
<?php endforeach; ?>
ORM offers many advantages, such as relationships, validation and filters. Without you having to write complex additional code (such as DB expressions).
Additionally when working on views, you might want to use a Controller that extends Controller_Template instead of Controller
来源:https://stackoverflow.com/questions/20351528/display-result-from-a-query