I’m currently passing a multidimensional char array to my MySQL function. cmd contains the command and resultSet[2][50] is my array.
How can I make this more dynamic so that I’m able to retrieve as many items as I want?
int
selectDB(char * cmd, char resultSet[2][50])
{
MYSQL *conn;
MYSQL_RES *result;
MYSQL_ROW row;
int i;
char *c1;
conn = mysql_init(NULL);
if (conn == NULL) {
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
if (mysql_real_connect(conn, "localhost", "root",
"mypassword", "myDBName", 0, NULL, 0) == NULL)
{
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
if (mysql_query(conn, cmd))
{
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
if (!(result = mysql_store_result(conn)))
{
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
while((row = mysql_fetch_row(result))) {
for (i=0 ; i < mysql_num_fields(result); i++)
{
snprintf(resultSet[i], 999, "%s", row[i]);
}
}
if (!mysql_eof(result))
{
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
mysql_free_result(result);
mysql_close(conn);
return 0;
}
You could accept a triple pointer as an argument like this and an
int, that will tell the size of the arrayThis way you’ll know the size of the array, but you’ll need to take care of freeing the memory, allocated for
resultSet.