首页 > 解决方案 > 致命错误:不能使用 CI_DB_mysql_result 类型的对象作为数组

问题描述

在发布此问题之前,我已阅读12和其他几个线程,但没有一个能解决我的问题。我对 PHP 完全陌生,并且一直在尝试使用 codeigniter 学习 MVC。导致错误的功能是

public function get_results() 
{ 
    $libraries = array("", "JQuery", "MooTools", "YUI Library", "Glow"); 
    $table_rows = ''; 

    for ($i = 1; $i < 5; $i++) 
    {
         $this->db->select('COUNT(choice) choices_count')->from('js_libraries')->where('choice',$i);
         $result = $this->db->get();
         $table_rows .= "<tr><td>" . $libraries[$i] . " Got:</td><td><b>" . $result[0] . "</b> votes</td></tr>"; 
         
    } 
 } 

我已经在 phpmyadmin 上执行了查询,它显示了结果(单个整数),但我无法使这个CI_DB_mysql_result对象工作。我已经尝试了所有result(), result_array(), getResult()函数,但它说这种对象的未定义函数。我怎样才能得到结果CI_DB_mysql_result

标签: phpcodeigniter

解决方案


好的。那是因为result_array返回包含表中多行的二维数组。在这种情况下,您只需要一行,因此您可以使用以下任一项:

  1. row()将结果作为对象返回的方法。 $result = $this->db->get()->row(); 然后$result->choices_count得到计数值。

  2. row_array()将结果作为数组返回的方法。 $result = $this->db->get()->row_array(); 然后$result['choices_count']得到计数值。

  3. unbuffered_row()将结果作为对象返回的方法 $result = $this->db->get()->unbuffered_row(); 然后$result->choices_count获取计数值。

  4. unbuffered_row('array')将结果作为数组返回的方法。 $result = $this->db->get()->unbuffered_row('array'); 然后$result['choices_count']得到计数值。


推荐阅读