I try to make function to check if table exists and to get total number of rows but I get result 1 instead of 99999.
So, what should I do here to work properly?
int sql_table_length(char* database, char* dtable, char* mysql_user_name, char* mysql_password)
{
int retval = 0;
MYSQL *conn;
conn = mysql_init(NULL);
if (conn)
{
if (mysql_real_connect(conn, "localhost", mysql_user_name, mysql_password, database, 0, NULL, 0)!=0)
{
char chktable[512] = {0};
sprintf(chktable,"%s%s%s", "SHOW TABLES LIKE '", dtable, "'");
mysql_query(conn, chktable);
if (mysql_store_result(conn))
{
MYSQL_RES *result;
char lngtable[512] = {0};
sprintf(lngtable, "%s%s", "SELECT COUNT(*) FROM ", dtable);
if (!(mysql_query(conn, lngtable)))
{
result = mysql_store_result(conn);
retval = mysql_num_rows(result); // here I get 1
mysql_free_result(result);
}
else retval = -4; //no rows
}
else retval = -3; //don't exist
}
else retval = -2; //can't connect
}
else retval = -1; //no connection
mysql_close(conn);
return retval;
}
Thanks!
Your query,
SELECT COUNT(*) FROM tablereturns a single row containing the number of rows in the table. Instead of counting the number of rows in the result, you want to query the number that is returned.You will want to do something like (untested):
You should add error checking to all the
mysqlcalls. See http://dev.mysql.com/doc/refman/5.0/en/mysql-stmt-fetch.html for more examples about binding parameters.Alternatively, you can change your query to something like
SELECT * FROM tableand keep the rest of your code, but this is asking MySQL to do a lot more work, and the result will likely take longer.