控制器函数在PHP中收集SQL数据

时间:2012-12-04 02:09:11

标签: php templates scope

我正在使用基于PHP的MVC框架

在我的控制器中,我有以下功能:

public function listing($tag=null, $page=1)
{
    $this->posts('`online`=1', $tag, $page, '%s/%d/');
    $this->locations('`parent`=1');
}

在同一个文件中,我有2个函数从2个MySQL表中收集数据,一个用于位置:

private function locations($query)
{   
    // Collect Locations
    $locations = new Locations('WHERE '.$query.' ORDER BY `name` ASC');
    $total_locations = $locations->count();

    // Template
    require Template::render('Posts', 'listing.html');
}

和另一个帖子:

private function posts($query, $tag, $page)
{
    // Collect Posts
    $posts = new Post('WHERE '.$query.' ORDER BY `date` DESC');
    $total_posts = $posts->count();
    $pages = ceil($total_posts/24);

        if($page < 1) $page = 1;
        if($page > $pages) $page = $pages;

        $min = $page - 4;
        $max = $page + 4;

        if($min < 1)
        {
            $max += 1 - $min;
            $min = 1;
        }

        if($max > $pages)
        {
            $min += $pages - $max;          
            if($min < 1) $min = 1;          
            $max = $pages;
        }

        $posts->query('LIMIT '.($page*24-24).',24');


    // Template
    require Template::render('Posts', 'listing.html');
}

在公共功能(列表)中,当第一行是$this->posts...时,它正确显示帖子但不显示位置(它只显示“数组”。

如果我先放$this->locations...,那么它会正确显示位置但不会显示帖子。

我没有向您展示更多代码,因为我认为它来自我listing function

中的写错误

如何显示两个阵列?

在我的视图页面上,我会显示这样的位置/帖子:

<?php while($location = $locations->fetch($i)): ?>
    <p>
         <?php echo $location->title; ?>
    </p>
<?php endwhile; ?>

2 个答案:

答案 0 :(得分:0)

我认为问题出在这里

require Template::render('Posts', 'listing.html');

我现在不知道这些参数意味着什么,但我的猜测是第一个是模板中变量的名称,对于它们两个你将它设置为帖子。

答案 1 :(得分:0)

通过合并2 private functions together并从$this->locations('

中删除=1');public function来解决此问题

设计被称为2次,一次是地点,另一次是帖子,因为我打了2次模板页面。

解决方案只是将两个功能合并在一起!