Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select column length in php (below PHP7)

Tags:

php

mysql

How do I get the actual max length of a specified column in php (prior to PHP7)?

For instance, this table:

id - int(11) name - string(20)

I want in php to select the maximum number of characters that a field can have, like

SELECT length(name) from table1

and it should then return 20 (since it's the maximum number of characters for that field).

like image 317
Patrick Avatar asked Jun 12 '10 12:06

Patrick


3 Answers

You should use mysql_field_len

http://php.net/manual/en/function.mysql-field-len.php

like image 184
newinjs Avatar answered Oct 03 '22 05:10

newinjs


You can use mysql_field_len for a single column or use the SHOW COLUMNS FROM table query in MySQL to get information about all the columns at once.

like image 20
Anax Avatar answered Oct 03 '22 04:10

Anax


Just be careful when using mysql_field_len to read columns that are not ints or strings. For example, decimal(6,4) will return 10 from mysql_field_len.

You may wish to use SHOW COLUMNS and parse the data, if you need all of the column information.

like image 40
David Snabel-Caunt Avatar answered Oct 03 '22 06:10

David Snabel-Caunt