(Swift,iOS)基于PHP脚本中使用的POST变量从mySQL数据库解析JSON对象


(Swift, iOS) Parsing JSON objects from mySQL database based on a POST variable used in a PHP script?

我目前正在开发一个iOS应用程序,该应用程序允许用户点击TableViewCells为歌曲投票。

我已经成功地从连接到mySQL表的PHP脚本中加载了带有解析的JSON对象(歌曲)的tableviewcells

我还成功地使用POST方法向数据库发布了一个查询。

然而,现在我正试图在查询中使用POST变量,该变量返回JSON对象供我解析。

以下是我使用POST方法更新数据库的脚本:

    let queryID = self.partyID[0]
    let queryGenre = self.recievedGenre
    var loadIntoVotes = "queryID='(queryID)&queryGenre='(queryGenre)"
    let URL: NSURL = NSURL(string: "http://myserverURL/loadSongsIntoTable.php")!
    let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
    request.HTTPMethod = "POST"
    request.HTTPBody = loadIntoVotes.dataUsingEncoding(NSUTF8StringEncoding);
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
        {
            (response, data, error) in
    }

下面是我解析返回JSON对象的脚本:

    let url=NSURL(string:"http://myserverURL/grabID.php")
    let allSongsData=NSData(contentsOfURL:url!)
    var allSongs: AnyObject! = NSJSONSerialization.JSONObjectWithData(allSongsData!, options: NSJSONReadingOptions(0), error: nil)
    if let json = allSongs as? Array<AnyObject> {

        for index in 0...json.count-1 {
            let songID : AnyObject? = json[index]

            let collection = songID! as Dictionary<String, AnyObject>
            let ID : AnyObject! = collection["ID"]

            self.partyID.append(ID as String)
        }
    }

因此,从本质上讲,我如何在PHP脚本中使用POST变量,然后根据返回的结果解析JSON?

不久前我也这么做了。我的PHP脚本看起来像:

<?php
    include 'database.php';
    // get data
    $data = $_POST['json'];
    $query = json_decode($data)->{'query'};
    // connecting to mysql
    $connection = mysql_connect($host, $username, $password);
    mysql_select_db($db_name, $connection);
    // check connection
    if (!$connection)
    {
        die("Couldn't connect: " . mysql_error());
    }
    $result = mysql_query($query, $connection);
    // check results
    if (!$result)
    {
        die("Error getting results: " . mysql_error());
    }
    if (mysql_num_rows($result))
    {
        while (($row = mysql_fetch_row($result)))
        {
            $array[] = $row;
        }
        mysql_close($connection);
        echo json_encode($array);
    }
    else
    {
        mysql_close($connection);
    }
?>

以及在objective-c++中:

std::vector<std::vector<std::string>> getQuery(std::string query)
{
    // convert cstring to obj-cstring
    NSString *getQuery = [NSString stringWithCString:query.c_str() encoding:NSUTF8StringEncoding];
    // create dict for json
    NSDictionary *jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:getQuery, @"query", nil];
    // initialize json
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    if (error)
    {
        NSLog(@"%s: JSON encode error: %@", __FUNCTION__, error);
    }
    // start request
    std::string num_rows_string = LOCALHOST;
    num_rows_string += "getQuery.php";
    NSURL *url = [NSURL URLWithString:[NSString stringWithCString:num_rows_string.c_str() encoding:NSUTF8StringEncoding]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSString *queryString = [NSString stringWithFormat:@"json=%@", [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSData *sendData = [queryString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:sendData];
    // execute request
    NSURLResponse *response = nil;
    NSData *getResult = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error)
    {
        NSLog(@"%s: NSURLConnection error: %@", __FUNCTION__, error);
    }
    // ----------DEBUGGING TESTS----------
    NSString *something = [[NSString alloc] initWithData:getResult encoding:NSASCIIStringEncoding];
    NSLog(@"GETRESULT: %@", something);
    // store result in array
    std::vector<std::vector<std::string>> data;
    if (getResult.length != 0)
    {
        NSArray *storeResult = [NSJSONSerialization JSONObjectWithData:getResult options:0 error:&error];
        if (error)
        {
            NSLog(@"%s: jSONObjectWithData error: %@", __FUNCTION__, error);
        }
        for (int i = 0; i < storeResult.count; i++)
        {
            NSArray *row = storeResult[i];
            std::vector<std::string> temp;
            for (int a = 0; a < row.count; a++)
            {
                temp.push_back([row[a] UTF8String]);
            }
            data.push_back(temp);
        }
    }
    return data;
}

您可能想要将objective-c代码更改为swift。不应该太难。