PHP mysqli_field_count() 函数



定义和用法

mysqli_field_count() 函数用于获取最近执行的 MySQL 查询结果集中的字段(列)数。

语法

mysqli_field_count($con)

参数

序号 参数及描述
1

con(必填)

这是一个代表与 MySQL 服务器连接的对象。

返回值

PHP mysqli_field_count() 函数返回一个整数值,表示上次查询结果集中的列数。如果上次查询不是 SELECT 查询(没有结果集),则此函数返回 0

PHP 版本

此函数首次引入于 PHP 5 版本,并在所有后续版本中均有效。

示例

以下示例演示了 mysqli_field_count() 函数(过程式风格)的用法:

<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   //Query to retrieve all the records of the employee table
   mysqli_query($con, "Select * from employee");

   //Field Count
   $count = mysqli_field_count($con);
   print("Field Count: ".$count);

   //Closing the connection
   mysqli_close($con);
?>

这将产生以下结果:

Field Count: 6

示例

在面向对象风格中,此函数的语法为 $con->field_count;,其中 $con 为连接对象:

<?php
   //Creating a connection
   $con = new mysqli("localhost", "root", "password", "mydb");

   //Query to retrieve all the records of the employee table
   $con -> query("Select FIRST_NAME, LAST_NAME, AGE from employee");

   //Field Count
   $count = $con->field_count;
   print("Field Count: ".$count);

   //Closing the connection
   $con -> close();
?>

这将产生以下结果:

Field Count: 3

示例

以下是另一个 mysqli_field_count() 函数的示例

<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   print("Field Count: ".mysqli_field_count($con)."\n");

   //INSERT Query
   mysqli_query($con, "INSERT INTO employee (FIRST_NAME, AGE) VALUES (Archana, 25), (Bhuvan, 29)");
   print("Field Count: ".mysqli_field_count($con));
  
   //Closing the connection
   mysqli_close($con);
?>

这将产生以下结果:

Field Count: 0
Field Count: 0

示例

<?php
   $connection_mysql = mysqli_connect("localhost","root", "password", "mydb");
   
   if (mysqli_connect_errno($connection_mysql)){
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
   
   mysqli_query($connection_mysql,"SELECT * FROM employee");
   print(mysqli_field_count($connection_mysql));
   
   mysqli_close($connection_mysql);
?>

这将产生以下结果:

6
php_function_reference.htm
广告