Documentation Home
MySQL 5.7 Reference Manual
Related Documentation Download this Manual
PDF (US Ltr) - 37.8Mb
PDF (A4) - 37.8Mb
PDF (RPM) - 36.4Mb
HTML Download (TGZ) - 9.8Mb
HTML Download (Zip) - 9.9Mb
HTML Download (RPM) - 8.6Mb
Man Pages (TGZ) - 209.5Kb
Man Pages (Zip) - 318.7Kb
Info (Gzip) - 3.5Mb
Info (Zip) - 3.5Mb
Excerpts from this Manual mysql_num_fields()

unsigned int mysql_num_fields(MYSQL_RES *result)

To pass a MYSQL* argument instead, use unsigned int mysql_field_count(MYSQL *mysql).


Returns the number of columns in a result set.

You can get the number of columns either from a pointer to a result set or to a connection handler. You would use the connection handler if mysql_store_result() or mysql_use_result() returned NULL (and thus you have no result set pointer). In this case, you can call mysql_field_count() to determine whether mysql_store_result() should have produced a nonempty result. This enables the client program to take proper action without knowing whether the query was a SELECT (or SELECT-like) statement. The example shown here illustrates how this may be done.

See Section, “Why mysql_store_result() Sometimes Returns NULL After mysql_query() Returns Success”.

Return Values

An unsigned integer representing the number of columns in a result set.



MYSQL_RES *result;
unsigned int num_fields;
unsigned int num_rows;

if (mysql_query(&mysql,query_string))
    // error
else // query succeeded, process any data returned by it
    result = mysql_store_result(&mysql);
    if (result)  // there are rows
        num_fields = mysql_num_fields(result);
        // retrieve rows, then call mysql_free_result(result)
    else  // mysql_store_result() returned nothing; should it have?
        if (mysql_errno(&mysql))
           fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
        else if (mysql_field_count(&mysql) == 0)
            // query does not return data
            // (it was not a SELECT)
            num_rows = mysql_affected_rows(&mysql);

An alternative (if you know that your query should have returned a result set) is to replace the mysql_errno(&mysql) call with a check whether mysql_field_count(&mysql) returns 0. This happens only if something went wrong.

User Comments
  Posted by on May 24, 2005
In the code in this example you have to watch out for the meaning of mysql_query() results. In fact it seems like from the example an INSERT that failed would return from mysql_query() successfully. You would also seem to guess that the num_rows value would be 0 in that case. Nothing could be further from the trust.

In fact, in an INSERT that fails because of duplicate keys, you will see mysql_query() fail and mysql_errno will return ER_DUP_ENTRY. This is ia little "gotcha" in this code.
Sign Up Login You must be logged in to post a comment.