Reputation: 13
I want to fetch results from my database (MySQL) and store them in an array. I tried some things, but I have no solution.
mysql_real_query(mysql, query, strlen(query));
mysql_res = mysql_store_result(mysql);
rows_number = (unsigned long) mysql_num_rows (mysql_res);
printf ("Number of Rows: %lu\n\n", rows_number);
while ((row = mysql_fetch_row (mysql_res)) != NULL) {
for (i = 0; i < mysql_num_fields(mysql_res); i ++)
printf ("%s ",row[i]); //this is printed like it should be.
printf("\n");
char *val = row[i]; //should save it to an char
printf("%s",val);
But if I start the program, the output is: (only extract!) This is what is send by printf ("%s ",row[i]); :
1 1 1 0006
And this is printed form char val:
</alias>
<alias>windows-1256</alias>
<collation name="cp1256_bin" id="67" order="Binary" flag="binary"/>
<collation name="cp1256_general_ci" id="57" order="Arabic" flag="primary">
<order>Arabic</order>
<order>Persian</order>
<order>Pakistani</order>
<order>Urdu</order>
</collation>
</charset>
So what is wrong? Thanks for your help!!
Upvotes: 1
Views: 2726
Reputation: 17258
i
is being used outside the bounds of the for loop:
Instead of :
for (i = 0; i < mysql_num_fields(mysql_res); i ++)
printf ("%s ",row[i]); //this is printed like it should be.
You probably meant this:
for (i = 0; i < mysql_num_fields(mysql_res); i ++)
{
printf ("%s ",row[i]); //this is printed like it should be.
printf("\n");
char *val = row[i]; //should save it to an char
printf("%s",val);
}
Upvotes: 1
Reputation: 74018
When you indent the code properly, you can see the problem
while ((row = mysql_fetch_row (mysql_res)) != NULL) {
for (i = 0; i < mysql_num_fields(mysql_res); i ++)
printf ("%s ",row[i]); //this is printed like it should be.
printf("\n");
char *val = row[i]; //should save it to an char
printf("%s",val);
The for loop is already finished, when you assign
char *val = row[i];
So, this is a classic off by one error.
Upvotes: 1