mysql api 返回查询结果,在MYSQL C API中处理SELECT查询结果的问题

I'm getting a Internal Server Error with one of my scripts. I'm using MYSQL C API. https://dev.mysql.com/doc/refman/5.6/en/c-api.html

Here is the corresponding part of my script:

MYSQL *con;

MYSQL_RES *result;

MYSQL_ROW robe;

con = mysql_init(NULL);

if (!mysql_real_connect(valid values)) {

printf("Content-type: text/html\n\n");

printf("Could not connect\n");

exit(0); }

char somequery[512];

//userinput is sanitized beforehand

int sog = sprintf(somequery, "SELECT password from testtab WHERE username='%s'", userinput);

if (sog < 0) {

printf("Content-type: text/html\n\n");

printf("Something went wrong with Sprintf\n");

exit(0); }

int bos = mysql_real_query(con, somequery, strlen(somequery));

if (bos != 0) {

printf("Content-type: text/html\n\n");

printf("The query produced no result\n");

exit(0); }

result = mysql_store_result(con);

if (result == NULL) {

printf("Content-type: text/html\n\n");

printf("No Result Set Produced\n");

exit(0); }

robe = mysql_fetch_row(result);

char *passdb = robe[0];

printf("Content-type: text/html\n\n");

printf("And it is: %s", passdb);

A HTML form submits via POST to this script (part of which is seen above). When I submit a username which exists in the database beforehand, I'm receiving no error. Everything works fine.

The problem arises, when I'm submitting a username that doesn't exist in the said table(testtab). Well, I'm getting 500 Internal Server Error. I have looked at Apache Error log as well: "End of Script output before Headers".

I have tried a few things so far, but none of them worked. Any help is appreciated.

Note: Doing mysql_num_fields(result); in both cases gives 1.

解决方案

I have found the solution elsewhere, thanks to the help of some good people. It seems, that I had made a silly mistake as well as needed a thorough understanding of the difference between two MYSQL C API functions.

I'm writing the answer here, in hope of it benefiting others.

The mistakes is here:

robe = mysql_fetch_row(result);

Though it is correct in itself. I fail to check its result. What happens is that when the SQL query is performed using a username that did not exist in the DB beforehand, the result is a empty set (and not a error).

The mysql_store_result and mysql_fetch_row have a slight difference here. While the former will not return NULL if the set is empty, the later will.

All I have to do is add a check after the above line with the logic:

if (robe == NULL) {

//error occured

} else { //go on

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值