Note that, if you want to get the amount of columns of a table and you're using the "SHOW COLUMNS FROM $table" query, you will have to use mysql_num_rows() instead of mysql_num_fields() on the result. This becomes logical when thinking about it, because the SHOW COLUMNS query returns a result with six columns (Field, Type, Null, Key, Default and Extra) and with a single row for every column found. If you'd count the number of fields, you'd always get 6. If you count the number of rows, you'll get the amount of columns found.
mysql_num_fields
(PHP 4, PHP 5)
mysql_num_fields — 結果におけるフィールドの数を得る
警告
この拡張モジュールは PHP 5.5.0 で非推奨になりました。将来のバージョンで削除される予定です。 MySQLi あるいは PDO_MySQL を使うべきです。詳細な情報は MySQL: API の選択 や それに関連する FAQ を参照ください。 この関数の代替として、これらが使えます。
説明
int mysql_num_fields
( resource
$result
)クエリから、フィールドの数を取得します。
返り値
成功した場合に結果セット resource のフィールド数、
失敗した場合に FALSE を返します。
例
例1 mysql_num_fields() の例
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
/* id,email の 2 つのフィールドがあるので、2 を返す */
echo mysql_num_fields($result);
?>
注意
注意:
下位互換のために、次の非推奨別名を使用してもいいでしょう。 mysql_numfields()
参考
- mysql_select_db() - MySQL データベースを選択する
- mysql_query() - MySQL クエリを送信する
- mysql_fetch_field() - 結果からカラム情報を取得し、オブジェクトとして返す
- mysql_num_rows() - 結果における行の数を得る
php at jezusisheer dot nl ¶
6 years ago
tharkey at tharkey dot net ¶
9 years ago
You can use it without a requete, just to list the fields :
$liste_champs = mysql_list_fields ( $Base, $Table, $connexion);
for ($i=0; $i < mysql_num_fields ($l_champs); $i++) {
echo ( mysql_field_name ($l_champs, $i) );
echo (' / ');
}
apass AT passmoore DOT com ¶
10 years ago
Adding to the last comment: you can dynamically loop through any number of columns AND rows like so-
$query="your SQL";
$result=mysql_query($query) or die("Query ($query) sucks!");
$fields=mysql_num_fields($result);
echo "<table>\n<tr>";
for ($i=0; $i < mysql_num_fields($result); $i++) //Table Header
{ print "<th>".mysql_field_name($result, $i)."</th>"; }
echo "</tr>\n";
while ($row = mysql_fetch_row($result)) { //Table body
echo "<tr>";
for ($f=0; $f < $fields; $f++) {
echo "<td>$row[$f]</td>"; }
echo "</tr>\n";}
echo "</table><p>";
This has been tested.
matt at iwdt dot net ¶
11 years ago
here's one way to print out a row of <th> tags from a table
NOTE: i didn't test this
$result = mysql_query("select * from table");
for ($i = 0; $i < mysql_num_fields($result); $i++) {
print "<th>".mysql_field_name($result, $i)."</th>\n";
}
post a comment if there's an error
bwark at stanford dot edu ¶
12 years ago
If you just want the number of fields in a table, you can do something like this:
<?php
$db_id = mysql_connet();
$result = mysql_query("DESCRIBE [tableName], $db_id);
$numFields = mysql_num_rows($result);
?>
Because "DESCRIBE" returns one row for each field in the table (at least in MySQL), this will work.
