PHP MySQLi 函数

PHP mysqli_result::fetch_field_direct() / mysqli_fetch_field_direct() 函数获取单个字段的元数据。它返回一个对象,其中包含指定结果集中的字段定义信息。

语法

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

//面向过程风格
mysqli_fetch_field_direct(result, index)

参数

result 必填。 仅适用于面向过程风格:指定 mysqli_query()、mysqli_store_result()、mysqli_use_result() 或 mysqli_stmt_get_result() 返回的 mysqli_result 对象。
index 必填。 指定字段编号。该值必须是 0 到(字段数 - 1)之间的整数。

返回值

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

对象属性

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

示例:面向对象风格

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

<?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)) {

  //获取"年龄"列的字段信息
  $finfo = $result->fetch_field_direct(1);

  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", $finfo->type);

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

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

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

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

示例:面向过程风格

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

<?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)) {

  //获取"年龄"列的字段信息
  $finfo = mysqli_fetch_field_direct($result, 1);

  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", $finfo->type);

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

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

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

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