4

I am trying to parse the MySQL data types returned by "DESCRIBE [TABLE]".

It returns strings like:

int(11)
float
varchar(200)
int(11) unsigned
float(6,2)

I've tried to do the job using regular expressions but it's not working.

PHP CODE:

$string = "int(11) numeric";<br/>
$regex = '/(\w+)\s*(\w+)/';<br/>
var_dump( preg_split($regex, $string) );<br/>
2
  • Why do you need to use regular expressions for this? What do you want to ultimately have once you've parsed the output? Commented May 26, 2010 at 21:59
  • parse it how? What do you want the end result to be? The contents of the parenthesis? Commented May 26, 2010 at 22:01

3 Answers 3

4

Query the information schema for introspection of tables and columns, and more.

Sign up to request clarification or add additional context in comments.

Comments

3

I wrote code to do this in Zend_Db_Adapter_Mysqli::describeTable().
It handles varchar, char, decimal, float, and all MySQL integer types.

I won't post the code here because of StackOverflow's CC-wiki license policy, but go check it out at that link.

mysql_fetch_field() only reports data types for query result sets, not persisted tables.

INFORMATION_SCHEMA is another option, but MySQL's early implementation of it has incredibly poor performance, which makes it hard to use in a web app that needs quick response time. Some changes in MySQL 5.1.23 tried to improve the performance, but some people still report problems.

3 Comments

Purely out of curiosity, does CC-wiki really conflict with the BSD license in a major way?
The CC Share-Alike license that SO uses requires attribution and it also requires that any work derived from the CC licensed code must also use a similar license. Not a conflict per se, but it muddies the terms of use.
This is exactly what I was looking for. I've already tested and it works PERFECTLY! :)
3

Why not just pull meta-data from the fields directly?

...
$meta = mysql_fetch_field($result, $i);
echo $meta->type;
echo $meta->max_length;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.