要获取字段,需要将表的名称作为参数


To fetch fields requires the name of the table as a parameter

我需要获取数据库表的表结构。所以我使用下面的代码。

class Some_model extends CI_Model{
    public $DB1;
    function __construct(){
        parent::__construct();
        $this->DB1 = $this->load->database('default',TRUE);
    }
    function getTableStructure($tableName){
        echo $tableName;     //this Outputs my table Name that i pass in the function
        return $this->DB1->field_data($tableName) ;   //this gives error for some tables
    }
}

我收到一个数据库错误

要获取字段,需要将表的名称作为参数

注意:此函数适用于某些表,但我在其他一些表中遇到此错误。我正在检查的表是"admin_user"

更新:

我已经检查了system/database文件夹中DB_driver.php文件中的field_data函数。

当我打印返回对象时,即

echo "<pre">;print_r($query->field_data());die();
//return $query->field_data();   commented this line print's the object

然而,

//echo "<pre">;print_r($query->field_data());die();  comment this line shows error. 
return $query->field_data();

我不知道为什么不通过调用来使用默认的DB配置

$this->db->field_data($tableName);

而是自定义变量DB1,因为您不会更改连接、数据库或任何显示或提及的内容。然而,下一个代码将像一个魅力:

public function desc1($tableName)
{
    $fields = $this->db->field_data($tableName);
    var_dump($fields);
}

或者你甚至可以使用自定义查询,比如:

public function desc2($tableName)
{
    $fields = $this->db->query("DESCRIBE `" . $tableName . "`");
    var_dump($fields->result());
}

这两个函数在返回的结果中略有不同,因此您必须检查它们,看看什么更适合您的代码(即自定义函数也会提供额外的字段)。

对我来说很好。

function getTableStructure($tableName){
  if(isset($tableName)){
     return $this->db->field_data($tableName) ;
     }
 }

检查!并确保表中没有用作字段名称的关键字。

错误消息说明您错过了什么
出现该错误时,$tableName为空
您可以查看system/database/DB_driver.phpfield_data(第878行可能是)函数。当$table(表名)为空时,您会收到错误消息
请确保表名不为空。

尝试用这个链接替换您的三个文件代码

https://github.com/bcit-ci/CodeIgniter/commit/effd0133b3fa805e21ec934196e8e7d75608ba00

文件是:-

system/database/drivers/mysql/mysql_result.php

system/database/drivers/mysqli/mysqli_result.php

user_guide_src/source/changelog.rst