-1

I want to list the number of columns in a MySQL database table with PHP. How can I achieve this?

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

2

The INFORMATION_SCHEMA built into every MySQL server can be used to find this information.

Try this query to get a list of each table in your current database along with its number of columns.

SELECT TABLE_NAME, COUNT(*) AS column_count
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE TABLE_SCHEMA=DATABASE()
 GROUP BY TABLE_NAME

If you want just one table's results, try something like this.

SELECT COUNT(*) AS column_count
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='mytable'
O. Jones
  • 103,626
  • 17
  • 118
  • 172
1

If you want to count number of columns then use

SELECT COUNT(*)
   FROM INFORMATION_SCHEMA.COLUMNS
   WHERE table_schema = 'database_name'
         AND table_name = 'tbl_name';
Arsalan Akhtar
  • 395
  • 2
  • 15