describe_table()
public function describe_table(string $table, bool $names_only = false): array|false
Description
Retrieves structural information about a database table using MySQL's DESCRIBE statement. This method can return either detailed column information or just column names. It's useful for dynamic form generation, validation, and understanding table schema at runtime.
Parameters
| Parameter | Type | Description | Default | Required |
|---|---|---|---|---|
| table | string | The name of the table to describe. | - | Yes |
| names_only | bool | If true, returns only column names. If false, returns full column details. | false | No |
Return Value
| Type | Description |
|---|---|
| array|false | Returns array of column details/names on success, or false on failure (e.g., table doesn't exist). |
Column Details Structure
When $names_only = false, each array element contains these keys:
| Key | Description | Example Value |
|---|---|---|
| Field | Column name | 'id', 'username', 'email' |
| Type | Data type with length/precision | 'int(11)', 'varchar(255)', 'decimal(10,2)' |
| Null | Whether NULL values are allowed ('YES' or 'NO') | 'NO', 'YES' |
| Key | Index information (PRI, UNI, MUL, or empty) | 'PRI', 'UNI', 'MUL', '' |
| Default | Default value or NULL | 'NULL', 'CURRENT_TIMESTAMP', '0' |
| Extra | Additional information (auto_increment, etc.) | 'auto_increment', '' |
Example #1: Getting Full Column Details
The code sample below demonstrates how to retrieve complete column information from the 'users' table.
Example #2: Getting Only Column Names
The code sample below demonstrates how to retrieve just the column names from the 'products' table.
Example #3: Using Column Information for Validation
The code sample below demonstrates how to use column information to validate data before insertion.
Important Notes
- The
$tableparameter is required. - Returns
falseon failure (e.g., table doesn't exist, database error). - Uses MySQL's
DESCRIBEstatement which is MySQL-specific (not portable to other databases). - When
$names_only = true, returns a simple indexed array of column names. - When
$names_only = false, returns an array of associative arrays with column details. - Useful for dynamic applications that need to adapt to different table structures.
- Consider caching results if calling frequently on the same table.
- For more detailed metadata, consider using
SHOW FULL COLUMNS FROMor queryingINFORMATION_SCHEMAdirectly.