display result from a query

时光怂恿深爱的人放手 提交于 2020-01-06 14:54:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!