mysql_num_fields

(PHP 4, PHP 5)

mysql_num_fields取得结果中字段的数量

警告

本扩展自 PHP 5.5.0 起已废弃,并在自 PHP 7.0.0 开始被移除。应使用 MySQLiPDO_MySQL 扩展来替换之。参见 MySQL:选择 API 指南来获取更多信息。用以替代本函数的有:

说明

mysql_num_fields(resource $result): int|false

从查询中检索字段的数量。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

返回值

Returns the number of fields in the result set resource on success 或者在失败时返回 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;
}

/* returns 2 because id,email === two fields */
echo mysql_num_fields($result);
?>

注释

注意:

为了向下兼容,可以使用下列已废弃的别名: mysql_numfields()

参见

添加备注

用户贡献的备注 3 notes

up
0
php at jezusisheer dot nl
17 years ago
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.
up
-2
matt at iwdt dot net
23 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
up
-5
bwark at stanford dot edu
23 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.
To Top