Gerdinando
Gerdinando

Reputation: 57

Sending a SQL query to PHP in Objective-C

I have googled and couldn't find any easy solution to do this. I know it's bad practice to send a SQL query to PHP but since the database can only be accessed locally, I don't have to worry about security issues just yet.

I have a function which requires a SQL query as argument. With this SQL query I want to send it to PHP to get the results. The only problem now is how to send the string to PHP.

So far my test Objective-C code looks like this:

void aFunction(std::string query)
{
    NSString *dictQuery = [NSString stringWithCString:query.c_str() encoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"query", dictQuery, nil];

    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    if (error)
    {
        NSLog(@"%s: JSON encode error: %@", __FUNCTION__, error);
    }

    NSURL *url = [NSURL URLWithString:@"http://localhost/test.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];
    NSString *params = [NSString stringWithFormat:@"json=%@", [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSData *paramsData = [params dataUsingEncoding:NSUTF8StringEncoding];

    // receive return value
    ...
}

test.php:

<?php
    $http_raw_post_data = $_POST['json'];

    $post_data = json_decode(stripslashes($http_raw_post_data),true);

    if (is_array($post_data))
    $response = array("status" => "ok", "code" => 0, "original request" => $post_data);
    else
    $response = array("status" => "error", "code" => -1, "original_request" => $post_data);

    include 'database.php';

    $connection = mysql_connect(SERVER, USER, PASSWORD);
    mysql_select_db(DATABASE, $connection);

    if (!$connection)
    {
        die("Couldn't connect: " . mysql_error());
    }

    $sql = $post_data;
    $result = mysql_query($sql, $connection);

    if (!$result)
    {
        die("Error getting results: " . mysql_error());
    }

    while (($row = mysql_fetch_row($result)))
    {
        $array[] = $row;
    }

    mysql_close($connection);

    echo json_encode($array);
?>

After checking the result, the string being sent returns: json=%7B%22select%20*%20from%20items%22:%22query%22%7D. How can I fix this?

Upvotes: 0

Views: 591

Answers (2)

Gerdinando
Gerdinando

Reputation: 57

OBJECTIVE-C:

void aFunction(std::string getQuery)
{       
    NSString *query = [NSString stringWithCString:getQuery.c_str() encoding:NSUTF8StringEncoding];

    // create dict for json
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:query, @"query", nil];

    // initialize json
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    if (error)
    {
        NSLog(@"%s: JSON encode error: %@", __FUNCTION__, error);
    }

    // start request
    NSURL *url = [NSURL URLWithString:@"http://localhost/test.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSString *params = [NSString stringWithFormat:@"json=%@", [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSData *paramsData = [params dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:paramsData];

    // execute request
    NSURLResponse *response = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error)
    {
        NSLog(@"%s: NSURLConnection error: %@", __FUNCTION__, error);
    }

    // examine the response
    NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"responseString: %@",responseString);
}

PHP:

$data = $_POST['json'];

$query = json_decode($data)->{'query'};

include 'database.php';

$connection = mysql_connect(SERVER, USER, PASSWORD);
mysql_select_db(DATABASE, $connection);

if (!$connection)
{
    die("Couldn't connect: " . mysql_error());
}

$result = mysql_query($query, $connection);

if (!$result)
{
    die("Error getting results: " . mysql_error());
}

while (($row = mysql_fetch_row($result)))
{
    $array[] = $row;
}

mysql_close($connection);

echo json_encode($array);

Upvotes: 0

MattLoszak
MattLoszak

Reputation: 585

Maybe URL decode it?

http://meyerweb.com/eric/tools/dencoder/

in php this is done with

$decoded = urldecode($string);

Upvotes: 2

Related Questions