tags:

views:

25

answers:

3

Hi, I was reading through our code base at my company and I saw something that seemed like it could be done better.

$dbRow = $dbh->Execute("SELECT * FROM database.table LIMIT 1");
$tableColumnCount = $dbRow->_numOfFields;

Is this the only way to get a column count using ADODB? It just seems silly to have to execute a query so you can ask the question.

+1  A: 

Whichever way, you'll have to end up hitting the database unless your program can magically know the schema of the table. If LIMIT 0 is legal in MySQL then this would be slightly more efficient - as I expect would replacing LIMIT 1 with WHERE 1 = 0.

Will A
I just think executing the query to get the column count kind of looks ugly. I was hoping their API would expose a call for this.
stevebot
If you want the count of columns it's not too bad, I suppose. I agree - it is a little ugly. A point well made though, Stevebot.
Will A
+2  A: 

You can use the INFORMATION_SCHEMA.COLUMNS table:

SELECT COUNT(*) 
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE table_name = 'your_table_name'
   AND table_schema = 'your_database_name'

That said, you might want to run the FLUSH TABLES command prior to for the INFORMATION_SCHEMA.COLUMNS to reflect existing tables and columns because the data is cached.

OMG Ponies
+1  A: 

MetaColumns or MetaColumnNames should give you this information

Mark Baker