Page 1 of 1

Count

Posted: Fri Nov 12, 2004 6:02 am
by Niko
Is there a way to count the number of columns in a table?
Even if the table has no data.

Posted: Fri Nov 12, 2004 6:19 am
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

Posted: Fri Nov 12, 2004 6:34 am
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'";
?>

Posted: Fri Nov 12, 2004 6:37 am
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'";
?>