PHP MySQLi 函数

PHP mysqli::$field_count / mysqli_field_count() 函数返回最近查询的列数由 mysql 参数表示的连接。当使用 mysqli_store_result() 函数来确定查询是否应该生成非空结果集而不知道查询的性质时,此函数非常有用。

语法

//面向对象风格
$mysqli->field_count;

//面向过程风格
mysqli_field_count(mysql)

参数

mysql 必填。 仅适用于面向过程风格:指定 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

返回一个整数,表示结果集中的字段数。

示例:面向对象风格

下面的示例显示mysqli::$field_count<的用法/i> 属性。

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

//执行SQL查询
$sql = "SELECT EmpID, Name, Age FROM Employee ORDER BY Age";
$mysqli->real_query($sql);

if ($mysqli->field_count) {
  //传输上次查询的结果集
  $result = $mysqli->store_result();

  //处理结果集
  $row = $result->fetch_row();

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

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

示例:面向过程风格

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

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

//执行SQL查询
$sql = "SELECT EmpID, Name, Age FROM Employee ORDER BY Age";
mysqli_real_query($mysqli, $sql);

if (mysqli_field_count($mysqli)) {
  //传输上次查询的结果集
  $result = mysqli_store_result($mysqli);

  //处理结果集
  $row = mysqli_fetch_row($result);

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

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