We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

I cannot recieve a describe of columns from database

Hi! I need to get information about table's columns. Requests ('SHOW COLUMNS FROM table_name', 'DESCRIBE table_name') not work. In documentation I found next example: https://docs.phalcon.io/ru/latest/reference/db.html#id14 This example shows use of the method "describeColumns". But I cannot repeat this example. In my case I recieve an object witch does not have public prorepties [as in example $field['Type']]:

[0] => Phalcon\Db\Column Object
        (
            [_columnName:protected] => id
            [_schemaName:protected] => 
            [_type:protected] => 0
            [_isNumeric:protected] => 1
            [_size:protected] => 10
            [_scale:protected] => 0
            [_unsigned:protected] => 1
            [_notNull:protected] => 1
            [_primary:protected] => 1
            [_autoIncrement:protected] => 1
            [_first:protected] => 1
            [_after:protected] => 
            [_bindType:protected] => 1
        )

I can use methods "getType", "getSize", "isNotNull" etc., but: 1) I need information about default value of the columns, but I don't see the similar field - the recieved object contains not all information 2) I need text value of the field's type but not numeric Please, explain to me how to recieve a column's decribe



31.3k

Hi, I encounter the same situation before and I endup with a custom solution like this one :

$connection = $this->db;

$result = $connection->query("describe tableName");
$result->setFetchMode(\Phalcon\Db::FETCH_ASSOC);

$fields = array();

while ($obj = $result->fetch()) {

    $type = explode('(', $obj["Type"]);

    $field = new Field();
    $field->FieldName = $obj["Field"];
    $field->FieldType = DatabaseType::getCorrespondingType($type[0]);
    $field->IsNull = (($obj["Null"] === "NO") ? false : true);

    $fields[] = $field;
}

<?php

class DatabaseType {

    static function getCorrespondingType($typeName) {

        switch ($typeName) {

            case("varchar"):
            case("text"): {

                return "Text";
            }

            case("decimal"):
            case("int"): {

                return "Numeric";
            }

            case("date"): {

                return "Date";
            }

            case("tinyint"): {

                return "Bool";
            }
        }
    }
}

<?php

class Field {

  /*array(6) (
      [Field] => (string) ID
      [Type] => (string) int(11)
      [Null] => (string) NO
  )*/

  /**
   *
   * @var string
   */
  public $FieldName;

  /**
   *
   * @var string
   */
  public $FieldType;

  /**
   *
   * @var boolean
   */
  public $IsNull;
}

Good Luck