get_option函数返回未定义的索引

时间:2015-04-06 06:21:35

标签: codeigniter

我是新的codeigniter学生。我为helper文件夹中的数据库(在function_helper.php中)获取选项值。但我无法得到任何结果

function get_option($name, $default = '') {

    $CI = &get_instance();

    $query =  $CI->db->get_where('setting',array('s_name'=>$name),1);

    $result = $query->result();

    return $result['s_value'];
}

我测试了result_array()row_array()而不是result(),但仍然会返回此错误:

A PHP Error was encountered

Severity: Notice

Message: Undefined index: s_value

Filename: helpers/functions_helper.php

Line Number: 27

更新1 print_r($result)返回Array( )

更新2 :我在主控制器中使用这个简单的代码但没有返回:

$query = $this->db->get('setting');

        foreach ($query->result() as $row)
            {
            echo $row->s_name;
            }

更新3 :将dbdriver从pdo更改为mysql update 2代码工作。但仍然为主要问题和重新生成返回相同的错误:Message: Trying to get property of non-object

更新4 :更新3 print_r($result);后返回:

Array ( [0] => stdClass Object ( [id] => 4 [s_name] => test [s_value] => bbbbbbbbbbbbb ) )

return $result->s_value;仍然会返回Message: Trying to get property of non-object

更新5:我发现答案我在新答案中发表

2 个答案:

答案 0 :(得分:0)

可能是您的查询没有返回任何行,在实际尝试访问它之前总是很好检查行数,如下所示:

function get_option($name, $default = '') {

    $CI = &get_instance();

    $query =  $CI->db->get_where('setting',array('s_name'=>$name),1);    
    $result = $query->result();

    if( $query->num_rows() > 0 ) {
        return $result->s_value;
    }
    return ""; //if now records found return something
}

答案 1 :(得分:0)

我找到了解决方案:

1:将DBdriver从pdo更改为mysqli。

2:这个功能:

function get_option($name, $default = '') {

    $CI = &get_instance();

    $query =  $CI->db->get_where('setting',array('s_name'=>$name),1);    
    $result = $query->row_array();

    if( $query->num_rows() > 0 ) {
        return $result['s_value'];
    }
    return $default; //if now records found return something
}