【问题标题】:Class returns integer instead of object while trying to get column data类在尝试获取列数据时返回整数而不是对象
【发布时间】:2014-03-15 22:40:49
【问题描述】:

刚刚进入 OOP,并从 mysql 查询更改为 PDO。我正在尝试创建一个将返回表的列名和元数据的类。这样我就可以为我使用的所有表输出复制/粘贴数据。我已经使用了这样一个基于 mysql 扩展的工具很长时间了,它会吐出诸如完整的 SELECT/INSERT/UPDATE 查询之类的变体。除其他外,我现在想为存储过程添加 DECLARE 列表 - 因此获取类型和长度等元数据是必不可少的。跨两种模式的大约 150 个表,这种自动化是必不可少的。

由于不确定 getColumnMeta 的可靠性,我寻找代码并在 Sitepoint answer 中找到了看起来不错的代码。我试图将它包装在一个类中并模仿它的原始上下文,但是当我尝试 echo 或 print_r 响应时,我只是得到一个数字 1。在尝试解决方案时,我也收到了“不是对象”错误消息。

这是调用代码

$db_host="localhost";
$db_username='root';
$db_pass='';
$db_name='mydatabase';
try{
    $db= new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass, array(PDO::ATTR_PERSISTENT=>false));
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
catch(PDOException $e){echo "Error: ".$e->getMessage()."<br />"; die(); }
include 'ColMetaData.php';   //the file containing the class for getting a column listing for each table
$coldat= new supplyColumnMeta($db);
$tablemet=$coldat->getColumnMeta('groups');   // a manual insertion of a table name for testing
echo $tablemet;

这是包含文件中的类 类 supplyColumnMeta{ 公共函数 __construct($db){ $this->db=$db;

    }
    /**
        *    Automatically get column metadata
    */
    public function getColumnMeta($table)
    {$this->tableName=$table;
        // Clear any previous column/field info
        $this->_fields = array();
        $this->_fieldMeta = array();
        $this->_primaryKey = NULL;

        // Automatically retrieve column information if column info not specified
        if(count($this->_fields) == 0 || count($this->_fieldMeta) == 0)
        {
            // Fetch all columns and store in $this->fields
            $columns = $this->db->query("SHOW COLUMNS FROM " . $this->tableName, PDO::FETCH_ASSOC);
            foreach($columns as $key => $col)
            {
                // Insert into fields array
                $colname = $col['Field'];
                $this->_fields[$colname] = $col;
                if($col['Key'] == "PRI" && empty($this->_primaryKey)) {
                    $this->_primaryKey = $colname;
                }

                // Set field types
                $colType = $this->parseColumnType($col['Type']);
                $this->_fieldMeta[$colname] = $colType;
            }
        }
        return true;
    }
    protected function parseColumnType($colType)
    {
        $colInfo = array();
        $colParts = explode(" ", $colType);
        if($fparen = strpos($colParts[0], "("))
        {
            $colInfo['type'] = substr($colParts[0], 0, $fparen);
            $colInfo['pdoType'] = '';
            $colInfo['length']  = str_replace(")", "", substr($colParts[0], $fparen+1));
            $colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : NULL;
        }
        else
        {
            $colInfo['type'] = $colParts[0];
        }   
        // PDO Bind types
        $pdoType = '';
        foreach($this->_pdoBindTypes as $pKey => $pType)
        {
            if(strpos(' '.strtolower($colInfo['type']).' ', $pKey)) {
                $colInfo['pdoType'] = $pType;
                break;
                } else {
                $colInfo['pdoType'] = PDO::PARAM_STR;
            }
        }       
        return $colInfo;
    }
    /**
        *    Will attempt to bind columns with datatypes based on parts of the column type name
        *    Any part of the name below will be picked up and converted unless otherwise sepcified
        *     Example: 'VARCHAR' columns have 'CHAR' in them, so 'char' => PDO::PARAM_STR will convert
        *    all columns of that type to be bound as PDO::PARAM_STR
        *    If there is no specification for a column type, column will be bound as PDO::PARAM_STR
    */
    protected $_pdoBindTypes = array(
    'char' => PDO::PARAM_STR,
    'int' => PDO::PARAM_INT,
    'bool' => PDO::PARAM_BOOL,
    'date' => PDO::PARAM_STR,
    'time' => PDO::PARAM_INT,
    'text' => PDO::PARAM_STR,
    'blob' => PDO::PARAM_LOB,
    'binary' => PDO::PARAM_LOB
    );  
}

【问题讨论】:

    标签: php mysql class pdo


    【解决方案1】:

    问题来了:

    public function getColumnMeta($table)
    {
        $this->tableName=$table;
        // Clear any previous column/field info
        $this->_fields = array();
        $this->_fieldMeta = array();
        $this->_primaryKey = NULL;
    
        // Automatically retrieve column information if column info not specified
        if(count($this->_fields) == 0 || count($this->_fieldMeta) == 0)
        {
            // Fetch all columns and store in $this->fields
            $columns = $this->db->query("SHOW COLUMNS FROM " . $this->tableName, PDO::FETCH_ASSOC);
            foreach($columns as $key => $col)
            {
                // Insert into fields array
                $colname = $col['Field'];
                $this->_fields[$colname] = $col;
                if($col['Key'] == "PRI" && empty($this->_primaryKey)) {
                    $this->_primaryKey = $colname;
                }
    
                // Set field types
                $colType = $this->parseColumnType($col['Type']);
                $this->_fieldMeta[$colname] = $colType;
            }
        }
        return true;//<<--- not returning an object/array!
    }
    

    您的getColumnMeta 方法返回一个布尔值true。这个值的字符串表示当然是 1。如果你想让这个方法返回所有的元数据,把 return 语句改成这样:

        return array(
            'fields'  => $this->_fields,
            'meta'    => $this->_fieldMeta,
            'primary' => $this->_primaryKey
        );
    

    您的代码也存在一些其他问题,但鉴于这 不是 codereview.stackexchange,我不会详细介绍。不过,我要说的是:请尝试遵循大多数主要参与者遵守的编码标准:这些标准可以在这里找到:PHP-FIG

    哦,如果你想显示元数据,不要echo他们,而是var_dumpprint_r他们,当你返回一个数组或一个对象。
    或者至少echo json_encode($instance-&gt;getColumnMeta($table)); 以获得返回值的正确字符串表示。

    【讨论】:

      猜你喜欢
      • 2011-11-25
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多