简体   繁体   English

使用ASIFormDataRequest进行简单的mysql查询

[英]Simple mysql query with ASIFormDataRequest

I'm trying to use ASIFormDataRequest for iphone to get some values from my mysql database. 我正在尝试使用ASIFormDataRequest for iphone从我的mysql数据库中获取一些值。

From the iphone I do this: 从iPhone我这样做:

NSURL *url = [NSURL URLWithString: ServerApiURLGet]; 
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: url]; 
[request setDelegate:self]; 
[request setPostValue:@"james" forKey:@"name"];

The request is send to a php files, which does this: 请求发送到php文件,执行此操作:

$con = mysql_connect("host","user","password");
mysql_select_db("table", $con);

$name = mysql_real_escape_string($_GET['name']); 
$query = mysql_query("SELECT score FROM `active_users` WHERE `nickname` ='$name';"); 

$result = mysql_fetch_array($query); 

sendResponse(200, json_encode($result));

And the response function: 而响应功能:

function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}

Back to the iphone, I try to read the information from the callback like this: 回到iphone,我尝试从回调中读取信息,如下所示:

- (void)requestFinished:(ASIHTTPRequest *)request
{        
NSDictionary *responseDict = [[request responseString] JSONValue];

NSLog(@"responseString: %@", [request responseString]);
NSLog(@"responseHeaders: %@", [request responseHeaders]);
NSLog(@"responseDict: %@", responseDict );
}

But it doesn't work. 但它不起作用。 I get the error: 我收到错误:

2012-03-12 08:33:57.657 Test[1991:707] -JSONValue failed. Error is: Unexpected end of input
2012-03-12 08:33:57.659 Test[1991:707] responseString: 

2012-03-12 08:33:57.660 Test[1991:707] responseHeaders: {
Connection = close;
"Content-Type" = "text/html";
Date = "Mon, 12 Mar 2012 07:33:58 GMT";
Server = "Apache/2.2.6 mod_auth_kerb/5.3 PHP/5.2.17 mod_fcgid/2.3.6";
"Transfer-Encoding" = Identity;
"X-Powered-By" = "PHP/5.2.17";
}
  2012-03-12 08:33:57.661 Test[1991:707] responseDict: (null)

Any help is very appreciated. 非常感谢任何帮助。 Thanks 谢谢

Edit: 编辑:

Same result if I pass in a simple array: 如果我传入一个简单的数组,结果相同:

    $newArray = array(
    "score1" => '1000', 
);

 sendResponse(200, json_encode($newArray)); 

Solved: 解决了:

When I changed _GET to _POST, it works. 当我将_GET更改为_POST时,它可以工作。 Thanks 谢谢

You're just sending your result to the iPhone without JSON encoding it, so the JSONValue on the iPhone side fails to understand the result. 您只是将结果发送到iPhone而没有JSON编码,因此iPhone端的JSONValue无法理解结果。

Try something like; 试试像;

sendResponse(200, json_encode($result));

to encode your result before sending it. 在发送之前对结果进行编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM