To get a list of columns and their data type by passing table name on MySQL and MSSQL databases.
Raw Query in MSSQL:
Raw Query in MySQL:
Appreciated for any feedback!
/** * Returns the list of columns and their data type by the table name on MySQL database. * @param $sqlConnection MySQL Database Connection Link * @param $tableName * @param bool $fullType * @return array */ private function getMySqlTableColumnAndTypeList($mysqlConnection, $tableName, $fullType = false) { $table = $mysqlConnection->select("DESCRIBE $tableName"); $fieldAndTypeList = []; foreach ($table as $field){ $type = ($fullType || !str_contains($field->Type, '('))? $field->Type: substr($field->Type, 0, strpos($field->Type, '(')); $fieldAndTypeList[$field->Field] = $type; } return $fieldAndTypeList; } /** * Returns the list of columns and their data type and nullable by the table name on MSSQL database. * @param $sqlConnection SQL Database Connection Link * @param $tableName * @return array */ private function getSqlTableColumnsWithDataTypes($sqlConnection, $tableName) { $tableInfo = $sqlConnection->select("SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '". $tableName . "'"); $fieldAndTypeList = []; foreach ($tableInfo as $field){ $isNullable = ($field->IS_NULLABLE == 'YES') ? true : false; $fieldAndTypeList[$field->COLUMN_NAME] = (object)['type' => $field->DATA_TYPE, 'nullable' => $field->IS_NULLABLE, 'isNullable' => $isNullable]; } return $fieldAndTypeList; }
Raw Query in MSSQL:
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'your_table_name';
Raw Query in MySQL:
DESCRIBE your_table_name;
Appreciated for any feedback!
No comments:
Post a Comment
Please post any queries and comments here.