Marco Sulla
Marco Sulla

Reputation: 15930

How to get the length of a database column?

I'm accessing a MySQL database using PDO in PHP. Say I have a table with a column of type CHAR(30), or INT(5):

  1. there's a way to get the column length (the values 30 and 5) from a PHP script using PDO, that is not database-specific?
  2. if not, there's a way to get that value using PDO anyway?
  3. if not, there's a way to get that value using PHP?

Upvotes: 1

Views: 2435

Answers (1)

tadman
tadman

Reputation: 211560

This informations should be available in the information_schema.columns table:

SELECT CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE FROM information_schema.columns WHERE TABLE_NAME = 'your_table_name'

There's different columns for string lengths (CHARACTER_MAXIMUM_LENGTH) and numerical lengths (NUMERIC_PRECISION).

Update:

To work-around a limitation/bug of MySQL where the lengths are not always reported correctly, it might be necessary to parse the definitions themselves and extract the number within brackets.

Upvotes: 2

Related Questions