Hexaflexagon
Hexaflexagon

Reputation: 21

mysql_num_rows is always returning 0

I use mysql_num_rows and this function returns always 0

This is my Code:

#include <mysql/mysql.h>
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;

conn = mysql_init(NULL);

if (!mysql_real_connect(conn, "", "", "", "", 0, NULL, 0)) {
  fprintf(stderr, "%s\n", mysql_error(conn));
  exit(1);
}

if (mysql_query(conn, "SELECT * FROM TEST"))
{
  printf("MySQL query error : %s\n", mysql_error(conn));
  exit(1);
}

res = mysql_use_result(conn);

printf("Rows: %d\n", mysql_num_rows(res));

while ((row = mysql_fetch_row(res)) != NULL)
    printf("Row1: %s | Row2: %s | Row3: %s \n", row[0], row[1], row[2]);

mysql_free_result(res);
mysql_close(conn);

And this is the Output

Rows: 0
Row1: 1 | Row2: 127.0.0.1 | Row3: Raspberry
Row1: 2 | Row2: 127.0.0.1 | Row3: Raspberry

MySQL client version: 5.5.44

Upvotes: 1

Views: 549

Answers (2)

Hexaflexagon
Hexaflexagon

Reputation: 21

i fixed the Problem with a cast to int and mysql_store_result!

printf("Rows: %d\n", (int)mysql_num_rows(res));

Upvotes: 1

vmachan
vmachan

Reputation: 1682

Try showing the number of records after the while loop like below

printf("Rows: %d\n", mysql_num_rows(res));

while ((row = mysql_fetch_row(res)) != NULL)
    printf("Row1: %s | Row2: %s | Row3: %s \n", row[0], row[1], row[2]);

printf("Rows: %d\n", mysql_num_rows(res));

As per the documentation, when you use mysql_use_result, the mysql_num_rows does not give you the proper number until after you have processed the records. To get it before you would need to use mysql_store_result.

Hope this helps

Upvotes: 2

Related Questions