开发者

Return a single value from CI model method

I've got a method that's meant to return a single value. Because ->result() returns an array I'm using the following to return the single value I'd like to get:

return array_pop($this->db->query($SQL)-&开发者_开发问答gt;result())->event_name;

while it works perfectly fine, I'm wondering if there's something built into CI that maybe I've missed in the documentation. I also use this same trick to return a single record:

return array_pop($this->db->query($SQL)->result());

Is there a better way to do this?


row_array() will return you the 1st row found as an array, and row() will return it as an object.

So instead of array_pop, you can use:

return $this->db->query($SQL)->row()->event_name;

OR

return $this->db->query($SQL)->row_array();

https://www.codeigniter.com/user_guide/database/results.html


When you do what Rocket suggested, you can get a single value by just picking from that array. For example, I used this query to get count of rows:

function getNumberOfArticles() {
    $result = $this->db->query("SELECT COUNT(id) AS returnVal FROM articles")->row_array();
    return $result['returnVal'];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜