【问题标题】:PHP: display data retrieved from database (Silverstripe CMS)PHP:显示从数据库中检索的数据(Silverstripe CMS)
【发布时间】:2014-10-13 18:10:37
【问题描述】:

我在使用 Silverstripe CMS 时遇到问题。 我有基本的 SQL 查询,我想在<ul><li> 菜单中显示哪些结果。这应该很容易,但我在浏览文档时失败了。我发现了一些更复杂的示例(项目、学生),但在我看来,应该存在一些更简单的方法来做到这一点。谁能帮忙或者给我一个提示?

总结一下:我想运行一个 db sql 查询并将数据显示为列表。

我的WishPage.php

class WishPage extends Page {
    // some code which is irrelevant for this matter, but works fine
}

class WishPage_Controller extends Page_Controller {

    private static $allowed_actions = array('AddNewWishForm');

    public function AddNewWishForm() {
        // here you can add data to db
    }

    // Now I would like to show it; and here is the problem.
    public function ShowWishList() {
    $records = DB::query ("SELECT Title FROM Wishes;");
    return $records;
    }

}

我的模板WishPage.ss

<% include SideBar %>
<div class="content-container unit size3of4 lastUnit">

<div id="WishForm">
    <h2>Try it</h2>
    $AddNewWishForm
</div>

</div>

更新
我的Wishes.php

<?php
class Wishes extends DataObject {
    private static $db = array(
        'Name' => 'Text',
        'Comment' => 'Text'
    );
}

【问题讨论】:

    标签: php silverstripe


    【解决方案1】:

    您可以只使用 SS 内置功能从数据库中获取条目:

    // returns the list of all wishes
    public function ShowWishList() {
        return Wishes::get();
    }
    

    在前端你可以:

    <ul>
    <% loop $ShowWishList %><li>$Name: $Comment</li><% end_loop %>
    </ul>
    

    这当然要求您有一个 DataObjects 列表。

    【讨论】:

    • 感谢您的更新! return Wishes::get(); 是否应该与表名匹配(称为 Whish)?如果是这样,我在以这种方式更新函数ShowWishList 后出现服务器错误。
    • 是的,“Wishes”来自 DataObject 的名称 - 与表名相同。您可以在此处找到有关如何创建 DataObject 及其表的更多信息:doc.silverstripe.org/framework/en/topics/datamodel您的 DataObject 是什么样的?
    • 我已经用有关 Wishes.php 的信息更新了我的问题。如果我在 WishPage.php 中使用return Wishes::get(); > function ShowWishList() 会显示“服务器错误”而不是预期的输出。
    • 您可以通过添加 Director::set_environment_type('dev'); 将站点置于开发模式到 mysite/_config.php 这将告诉你错误实际上是什么。听起来您已经创建了一个名为 Whish 的 DataObject,然后运行了一个开发/构建,然后将其更改为 Wish。也许运行另一个应该创建 Wish 数据库表的开发/构建。
    【解决方案2】:

    spekulatius 的决定应该运作良好。

    如果你不尝试SQLQuery

    public function getWishes(){
        $query = new SQLQuery();
        $query->setFrom('Wishes')->setSelect('"Name", "Comment"');
        //$query->addWhere('');
        $result = $query->execute();
        //Debug::show($result);
        $list = ArrayList::create();
        foreach($result as $row) {
            $list->push($row);
        }
        return $list;
    }
    

    在主题中

    <ul>
        <% loop $getWishes %><li>$Name: $Comment</li><% end_loop %>
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多