In PHP, when we use the MySQLi extension to execute database queries, it is often necessary to know how many fields (columns) are included in the returned result set. This is especially useful when dynamically handling query results, such as constructing tables or exporting data.
mysqli_result::field_count is a property of the mysqli_result class used to get the total number of fields in a query result set. This article will explain its usage and provide a code example to help you better understand it.
mysqli_result::field_count is a read-only property that represents the number of fields in the query result set. Note that this number refers to the number of columns, not the number of rows returned.
Syntax:
$number_of_fields = $result->field_count;
Here, $result is the mysqli_result object returned by mysqli_query or $mysqli->query().
Here is a complete example demonstrating how to use mysqli_result::field_count to get the number of fields in a query result.
<?php
// Database connection info
$host = 'localhost';
$user = 'root';
$password = 'your_password';
$database = 'your_database';
<p>// Create connection<br>
$mysqli = new mysqli($host, $user, $password, $database);</p>
<p>// Check connection<br>
if ($mysqli->connect_error) {<br>
die('Connection failed: ' . $mysqli->connect_error);<br>
}</p>
<p>// Execute query<br>
$query = "SELECT id, name, email FROM users";<br>
$result = $mysqli->query($query);</p>
<p>// Check if query was successful<br>
if ($result) {<br>
// Get the number of fields<br>
$field_count = $result->field_count;<br>
echo "The number of fields in the query result: $field_count\n";</p>
while ($field = $result->fetch_field()) {
echo "Field name: " . $field->name . "\n";
}
// Free result set
$result->free();
} else {
echo "Query failed: " . $mysqli->error;
}
// Close connection
$mysqli->close();
?>
We connect to the database and execute a SELECT query.
We use $result->field_count to get the total number of returned fields.
We use the fetch_field() method to loop through the field details and output the name of each field.
Finally, we free the result set and close the database connection.
Dynamic Table Rendering: When you need to render query results as a table on a webpage, knowing the number of columns in advance helps you dynamically generate the table header.
Export Tools: When exporting to CSV or Excel, you need to loop through the field names to create the first row.
Debugging and Logging: During development, recording the number of fields returned by a query helps troubleshoot errors.