【问题标题】:How to get single row CodeIgniter如何获取单行 CodeIgniter
【发布时间】:2017-11-09 15:32:57
【问题描述】:

当我调用“conversationID”时如何获得单行,

现在当我调用“conversationID = 0”时,它会将所有“conversationID”显示为 0

消息表,

|ID|conversationID|from|to|
|1|0|3|4
|2|0|4|3
|3|0|3|4
|4|1|2|4
|5|1|4|2

控制器

public function index()
{
    $conversations_inbox = $this->conversation_model->get_conversation_inbox($this->user->info->ID);
    $this->template->loadContent("conversations/index.php", array("conversations_inbox" =>  $conversations_inbox,)
    );
}

型号

public function get_conversation_inbox($userid) {
        $query = $this->db->where("conversations.from_user = ". $userid)->or_where("conversations.to_user = ". $userid)->select("*")->from("conversations")->join("conversation_message", "conversation_message.conversationID = conversations.conversationID")->order_by("conversation_message.date", "DESC")->get();
        return $query->row();
    }


<?php
foreach ($conversations_inbox as $c) { ?>
<li class="mail-starred">
    <div class="mail-from"><a href="<?php echo base_url("conversations/message/") . $c['conversationID'] ?>"><img src="<?php echo base_url() . $c['store_picture'] ?>" style="width: 40px;height: 40px;margin-right: 10px;">
    <?php echo $c['store_name'] ?></a></div>
    <div class="mail-subject">
    <a href="<?php echo base_url("conversations/message/") . $c['conversationID'] ?>">Test</a>
    </div>
</li>
<?php } ?>

【问题讨论】:

  • return $query-&gt;row();

标签: php mysql codeigniter


【解决方案1】:

您正在使用$query-&gt;result(),它返回一系列可能的结果,如果您只需要一条记录,您应该使用$query-&gt;row()

您可以在此处阅读有关从文档返回结果的更多信息:https://www.codeigniter.com/user_guide/database/results.html#result-rows

【讨论】:

  • 获取错误信息:试图获取非对象的属性
  • 您可以使用 $varName['fieldName'] 访问数组符号的变量,如果它是对象:$varName-&gt;fieldName。检查print_r($conversations_inbox) 的输出。并相应地使用语法。参考:stackoverflow.com/questions/5175161/…
  • 是的,我得到了输出,但是如何进行 foreach?
  • 输出是数组还是对象?请标记为答案并编辑您的问题,以便我为您提供帮助。
  • 输出为数组,
【解决方案2】:

您可以通过以下方式获得具有数组属性的单行:

$row = $query->row_array()

然后您可以通过表格示例获取属性:

if ($row) {
    echo $row['ID'];
    echo $row['conversationID'];
    echo $row['from'];
    echo $row['to'];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 2015-05-31
    • 2023-04-10
    相关资源
    最近更新 更多