MySQL number of columns in a table

  • CreatiVe.RO
  • Newbie
  • Newbie
  • User avatar
  • Posts: 6

Post 3+ Months Ago

how can i get the number of the columns of a table?
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • ilyawizard
  • Proficient
  • Proficient
  • ilyawizard
  • Posts: 413

Post 3+ Months Ago

I'm not quite sure if there's mysql command for this, but you can select all the items from database, and then count the array:

$q=@mysql_query("SELECT * FROM table_name");
$info=@mysql_fetch_array($q);
echo count($info)+1." columns";
  • stalk
  • Novice
  • Novice
  • User avatar
  • Posts: 30

Post 3+ Months Ago

Wizard, I think that would count the rows in a table. If that's what the poster wants, just do

Code: [ Select ]
SELECT COUNT(*) FROM table


If he really wants to know the number of columns in a table, then use this query:

Code: [ Select ]
DESCRIBE table
  • knexor2
  • Proficient
  • Proficient
  • User avatar
  • Posts: 445
  • Loc: US

Post 3+ Months Ago

Wizard's method would list the number of columns in the table, but plus one. mysql_fetch_array returns an array of values in association with the column headers for the table.
  • stalk
  • Novice
  • Novice
  • User avatar
  • Posts: 30

Post 3+ Months Ago

You're right.. I missed the php count() function in his solution. ;)

I still think it'd be more straightforward to use DESCRIBE and do a mysql_num_rows() on the result set.
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

just as a matter of interest, a column is not the same as a row.

The number of columns is the same as the as the number of fields a complete row has.

I just remembered something. If I am correct there is a php mysql_num_fields which will return the number of fields in the result set.

Now this might sound cool but remember if you specify the fields to be returned then that is the number of fields the function will return not the entire table number of fields.

If you want the number of rows in a table use the COUNT(*) function if it is only the number and the mysql_num_rows if you are returning a result set

Post Information

  • Total Posts in this topic: 6 posts
  • Users browsing this forum: No registered users and 65 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.