PHP + PDO/MySQL: how to automatically query to find out VARCHAR field lengths?
Question
is there a way to use PHP+PDO to query a MySQL database and find out the column widths of some VARCHAR fields? I don't want to hardcode them into my PHP file if possible.
(purpose: determine maximum lengths of strings to be either inserted into these columns, or compared against existing data in the columns.)
Solution
Read it from INFORMATION_SCHEMA COLUMNS
OTHER TIPS
Just shoot a query to the information_schema
.columns
table and filter out the row you need. The value you're looking for is stored under 'CHARACTER_MAXIMUM_LENGTH'.
Run this query: 'DESCRIBE table_name
' where table_name is the name of the table you're looking for information about. It'll return what you're looking for.
Select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME='yourcolumn' and TABLE_NAME='yourtable';