douwei1128 2013-07-04 14:53
浏览 61
已采纳

我应该如何修改我的php webservice以处理一个而不是多个?

I have an iOS app that fetches users' points from a webservice using this method:

+(void)fetchPointsForUser:(NSString*)usuario WithCompletionHandler:(Handler2)handler{
    NSURL *url = [NSURL URLWithString:@"http://myserver.com/myapp/readpoints.php"];
    NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:usuario, @"userNa", nil];

    NSData *postData = [self encodeDictionary:postDict];

    // Create the request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    __block NSArray *pointsArray = [[NSArray alloc] init];

    dispatch_async(dispatch_get_main_queue(), ^{
        // Peform the request
        NSURLResponse *response;
        NSError *error = nil;
        NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
                                                     returningResponse:&response
                                                                 error:&error];
        if (error) {
            if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
                NSLog(@"HTTP Error: %d %@", httpResponse.statusCode, error);
                return;
            }
            return;
        }

        NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

        pointsArray = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSASCIIStringEncoding] options:0 error:nil];

        if (handler)
            handler(pointsArray);
    }); 

}

However this is very expensive because I basically enumerate through a usersArray and send the individual user each time, to this class method. So Im thinking I should modify my webservice to handle a different request where I send it the dictionary instead of the individual users.

My current php for this looks like this:

<?php

include_once("JSON.php");
$json = new Services_JSON();

$link = mysql_pconnect("localhost", "user", "pass") or die("Could not connect");
mysql_select_db("mydb") or die("Could not select database");

$username = $_POST["userNa"];
$result = mysql_query("SELECT username, SUM(points) AS PUNTOS FROM tags WHERE username='$username' GROUP BY username");


// Print out result
while($row = mysql_fetch_array($result)){
    echo $row['SUM(points)'];
}

// THIS RETURNS ARRAY NOT READ PROPERLY BY iOS JSON
$resultado = array();
while($obj = mysql_fetch_object($result)) {
    $resultado[] = $obj;
}
Echo $json->encode($resultado);

?>
  • 写回答

1条回答 默认 最新

  • dongzai2952 2013-07-04 16:10
    关注

    Correct me if I am wrong.

    You have a web service - input value is "UserName" and output is points against that UserName. And you have a list of UserName so you have to call this web service one by one.

    Why not change your web service to: input value is "list of UserName" and output is "list of points" then? It would let you app only call web service one time. But you need to change your web service calling function in iOS.

    In the web service (PHP), the mysql_query is basically a string and you can generate a mysql_query string programmatically according to input (list of UserName) and return data you need.

    I am not the right person to answer php script but I can give some idea how to create a query string. The following code is just idea.

    //You have a list of Username - $array
    //If array count is zero then just return
    //If array has data then do the follow logic
    //Generate your Query string programmatically
    $query_string = "SELECT username, SUM(points) AS PUNTOS FROM tags WHERE username = ".$array[0] ;
    
    for ($i = 1; $i < count($array); $i++){
        $query_string .= " OR username=".$array[$i];
    }
    
    $query_string .= " GROUP BY username";
    
    //print your query string and try it from PHP Admin, If it runs OK then you create it successfully
    
    $result = mysql_query($query_string);
    //$result is here is nothing but a result table
    //Then return it using json format
    

    Hopefully this can help you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?