【问题标题】:Controller function collecting SQL data in PHP在 PHP 中收集 SQL 数据的控制器函数
【发布时间】:2012-11-21 14:45:53
【问题描述】:

我正在使用基于 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-&gt;posts... 时,它正确显示帖子但不显示位置(它只显示“数组”。

如果我把$this-&gt;locations...放在第一位,那么它会正确显示位置而不是帖子。

我不会向您展示更多代码,因为我相信它来自我的 listing function 中的一个书写错误

如何显示两个数组?

在我的查看页面上,我会显示类似的位置/帖子:

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

【问题讨论】:

    标签: php templates scope


    【解决方案1】:

    我认为问题出在这里

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

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

    【讨论】:

    • 很好,但实际上第一个参数是文件夹的名称 my_path/Posts/listing.html 所以它们都是相同的,因为我希望 2 个数组显示在同一页面上
    • 这个文件中除了开头的&lt;?php class Ads extends Controller {外没有其他内容
    • 数据正确,但实际上设计在同一页面上显示了两次:一次显示位置但没有帖子,第二次没有位置但显示帖子。
    • 因为您从不同的方法和位置渲染它两次,并且帖子是局部变量。将它们移动到 $this->post 和 $this->locations 并从列表中调用模板。
    • 是的,模板被调用了 2 次!现在已经解决了,谢谢帮助!
    【解决方案2】:

    通过合并 2 个 private functions together 并从 public function 中删除 $this-&gt;locations('parent=1'); 解决了这个问题

    设计被调用了 2 次,一次是位置,另一次是帖子,因为我调用了模板页面 2 次。

    解决方案就是将这两个函数合并在一起!

    【讨论】:

      猜你喜欢
      • 2019-02-16
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      相关资源
      最近更新 更多