我想从我的数据库(MySQL)中获取结果并将它们存储在一个数组中。我尝试过一些东西,但我没有办法解决。
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);
但是如果我启动程序,输出是:(只提取!) 这是printf发送的内容(&#34;%s&#34;,row [i]); :
1 1 1 0006
这是打印形式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>
那有什么不对? 谢谢你的帮助!!
答案 0 :(得分:0)
当您正确缩进代码时,您可以看到问题
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);
分配
时,for循环已经完成char *val = row[i];
所以,这是一个经典的错误。
答案 1 :(得分:0)
i
在for循环的边界之外使用:
而不是:
for (i = 0; i < mysql_num_fields(mysql_res); i ++)
printf ("%s ",row[i]); //this is printed like it should be.
你可能意味着这个:
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);
}