Count

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Niko
Forum Newbie
Posts: 9
Joined: Tue Apr 20, 2004 6:17 am

Count

Post by Niko »

Is there a way to count the number of columns in a table?
Even if the table has no data.
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post by kettle_drum »

A table being in a database? If so you use count()

Code: Select all

SELECT count(*) FROM blah WHERE moo = 'yes';
Edit: Reminds self the difference between rows and columns and points you in the direction of mysql_num_fields(); or mysql_list_fields(); or count the number of results from something like:

Code: Select all

SHOW COLUMNS FROM sometable
User avatar
scorphus
Forum Regular
Posts: 589
Joined: Fri May 09, 2003 11:53 pm
Location: Belo Horizonte, Brazil
Contact:

Post by scorphus »

If the DBMS is MySQL, I belive that a way to do this is as follows:

Code: Select all

<?php
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$sql = 'desc cities';
$result = mysql_query($sql);
$numCols = mysql_num_rows($result);
echo "There are $numCols columns in table 'cities'";
?>
User avatar
scorphus
Forum Regular
Posts: 589
Joined: Fri May 09, 2003 11:53 pm
Location: Belo Horizonte, Brazil
Contact:

Post by scorphus »

... or as kettle_drum pointed out:

Code: Select all

<?php
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$sql = 'SHOW COLUMNS FROM cities';
$result = mysql_query($sql);
$numCols = mysql_num_rows($result);
echo "There are $numCols columns in table 'cities'";
?>
Post Reply