Codeigniter SQL查询返回单个值

时间:2017-07-27 11:43:10

标签: php sql codeigniter

我正在使用CodeIgniter,我希望从表中获取最高的ID。这我在模型中实现了一个功能。但我没有得到结果,这是一个单一的价值,作为价值回归。

代码:

 function get_highest_answer_id(){
   $this->db->query('SELECT MAX(id) AS answerid FROM pa_it_answer;');
    if ($query = $this->db->get()) {
        if ($query->num_rows() > 0) {
            return $query->result();
        } else {
            return array();
        }
    } else {
        return FALSE;
    }
}

我如何更改在控制器中调用此函数时获得单个值的代码?

4 个答案:

答案 0 :(得分:2)

下面的代码对我来说很好。

{{1}}

答案 1 :(得分:0)

试试这个:

function get_highest_answer_id(){
   $this->db->query('SELECT MAX(id) AS answerid FROM pa_it_answer;');
    if ($query = $this->db->get()) {
        if ($query->num_rows() > 0) {
            return $query->row(); // here!!!
        } else {
            return array();
        }
    } else {
        return FALSE;
    }
}

我建议使用CI (已编辑)

querybuilder
$this->db->select_max('id', 'answerid');
$query = $this->db->get('pa_it_answer');

var_dump( $query );
var_dump( $query->answerid );
die();

答案 2 :(得分:0)

在codeigniter中更改您的查询

# -*- coding: utf-8 -*- 
from __future__ import unicode_literals
import requests
import json
import sys  

reload(sys)  
sys.setdefaultencoding('utf8')

def extractCommentFromPage(page_name):
    ACCESS_TOKEN = '*REDACTED*'
    base_url = 'https://graph.facebook.com/'
    node = base_url + page_name + '/feed/'
    fields = 'comments{message}'
    url = '%s?fields=%s&access_token=%s' % (node, fields, ACCESS_TOKEN,)
    page_name_File = open('unclassified/' + page_name + '.txt','w')
    web_response = requests.get(url)
    j = web_response.json()

    i = 0
    comments = []
    try:
        for k in j['data']:
            for e in k['comments']['data']:
                i = i + 1
                print 'Extracting comments from ' + page_name + ' #' + str(i)
                comments.append(e['message'].encode('utf-8'))
                page_name_File.write(e['message'].encode('utf-8') + "\n\n")
    except Exception as e:
        print e.message
        pass
    return set(comments)

答案 3 :(得分:0)

您只需使用row()

简化方法即可
function get_highest_answer_id(){
        $record = $this->db->query('SELECT MAX(id) AS answerid FROM pa_it_answer;')->row();
        if ($record) {
            return $record->answerid;
        } 
        else {
            return FALSE;
        }
    }