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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算