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

我应该如何修改我的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);

?>

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.