PHP MySQLi 函数

PHP mysqli_result::fetch_field() / mysqli_fetch_field() 函数返回结果集中一列的定义作为一个对象。可以重复调用该函数来检索结果集中所有列的信息。

语法

//面向对象风格
public mysqli_result::fetch_field()

//面向过程风格
mysqli_fetch_field(result)

参数

结果 必填。 仅适用于面向过程风格:指定 mysqli_query()、mysqli_store_result()、mysqli_use_result() 或 mysqli_stmt_get_result() 返回的 mysqli_result 对象。

返回值

返回一个包含字段定义信息的对象,如果没有可用的字段信息,则返回 false。

对象属性

td>
属性描述
名称名称列
orgname原始列名称(如果指定了别名)
table该字段所属的表的名称(如果未计算)
orgtable如果指定了别名,则原始表名称
def保留为默认值,当前始终为""
db数据库的名称
目录目录名称,始终为"def"
max_length结果集字段的最大宽度
长度字段的宽度,如在表定义
charsetnr字段的字符集编号
flags 表示字段位标志的整数
类型用于此字段的数据类型
小数使用的小数位数(用于整数字段)

示例:面向对象样式

下面的示例显示了 mysqli_result::fetch_field() 方法的用法。

<?php
//建立与数据库的连接
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

//从数据库获取查询结果
$sql = "SELECT Name, Age FROM Employee ORDER BY Age";

if ($result = $mysqli->query($sql)) {

  //获取所有列的字段信息
  while ($finfo = $result->fetch_field()) {

    //获取字段指针偏移量
    $currentfield = $result->current_field;

    printf("Column %d:\n", $currentfield);
    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);
  }

  //释放与结果相关的内存
  $result->close();
}

//关闭连接
$mysqli->close();
?>

上述代码的输出将类似于:

>
Column 1:
Name:     Name
Table:    Employee
max. Len: 50
Flags:    1
Type:     254

Column 2:
Name:     Age
Table:    Employee
max. Len: 10
Flags:    32769
Type:     4

示例:面向过程风格

下面的示例显示mysqli_fetch_field()函数的用法。

<?php
//建立与数据库的连接
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

//从数据库获取查询结果
$sql = "SELECT Name, Age FROM Employee ORDER BY Age";

if ($result = mysqli_query($mysqli, $sql)) {

  //获取所有列的字段信息
  while ($finfo = mysqli_fetch_field($result)) {

    //获取字段指针偏移量
    $currentfield = mysqli_field_tell($result);

    printf("Column %d:\n", $currentfield);
    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);
  }

  //释放与结果相关的内存
  mysqli_free_result($result);
}

//关闭连接
mysqli_close($mysqli);
?>

输出上面的代码将类似于:

Column 1:
Name:     Name
Table:    Employee
max. Len: 50
Flags:    1
Type:     254

Column 2:
Name:     Age
Table:    Employee
max. Len: 10
Flags:    32769
Type:     4