1

I am currently developing an iOS application that allows users to tap TableViewCells to vote for a song.

I have successfully been able to load the tableviewcells with parsed JSON objects (songs) from a PHP script connecting to a mySQL table with the songs in it.

I have also successfully posted a query to the database using POST method.

However, now I am trying to utilize a POST variable in my query that returns JSON objects for me to parse.

Below is my script for update the database utilizing POST method:

    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

    }

And here is my script for parsing returned JSON objects:

    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)

        }
    }

So essentially, how can I utilize a POST variable in my PHP script and then parse JSON based on the returned results?

Sam Carter
  • 71
  • 3
  • I'm not 100% sure what the question is here, but make sure to percent escape when building the query. And make sure to escape the strings (e.g. `mysqli_real_escape_string`) before using them in sql. See http://stackoverflow.com/a/20196541/1271826. – Rob Mar 30 '15 at 01:36

1 Answers1

0

A while ago I did the same. My PHP script looked like:

<?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);
    }
?>

and in 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;
}

You might want to change the objective-c code to swift. Shouldn't be too hard.

Henny Lee
  • 2,970
  • 3
  • 20
  • 37