0

I'm currently working on an iOS app, which communicates with a database on a server (REST API). I've managed to send simple post queries to the server and successfully getting responses, but since a few hours I am stuck with the following php-function (it was not written by myself!). My questions:

  1. Is this valid php-Code?

  2. Is it possible to POST both JSON-Objects and non-JSON Objects at the same time?

  3. How would a valid request query look like? (I am using the Google Chrome App "Postman - REST Client" to test the queries) So what would the parameters look like if a wanted to pass tableid = 1, clientid = 1 and json = {1,2,3,4}?

Thank you very much!

if($_POST['function'] == 'addOrder'){

    $sql = "INSERT INTO orders SET
                orderdate = NOW(),
                tableid = '".$_POST['tableid']."',
                clientid = '".$_POST['clientid']."'";
    $result = mysql_query($sql);
    $oid = mysql_insert_id();

    $orderitems = json_decode($_POST['json'],true);

    reset($orderitems);
    while(list(,$oitem) = each($orderitems)){
        $sql = "INSERT INTO orderitems SET
                        orderid = '".$oid."',
                        foodid = '".$oitem['id']."";    
        $result = mysql_query($sql);
    }
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
Crumble
  • 13
  • 1
  • 1
    This code will be susceptible to SQL injection attacks. I'd suggest you review http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php. For example, use `mysql_real_escape_string` on your variables, or use parameterized binding of the variables. But the way you've got it now, you're open to SQL injection attacks (or simple syntactic error if your strings have single quotes in them). – Rob Aug 23 '13 at 02:03
  • Okey, I get your point - thanks! Apart from the security issue: Can I send a JSON Object AND Strings (addOrder, tableid, clientid) in one single request? As far as I know, one must specify the type of objects which are sent via the request (JSON or text, but not both). Am I right? At the moment I get the following error message, when sending my request to the server: "Variable passed to each() is not an array or object in domains/XY....." I create the Object by using "NSJSONSerialization" on a NSData made out of an array of Dictionaries (e.g. one Dictionary is "id" : "1") – Crumble Aug 24 '13 at 00:48
  • By the way, while you can mix simple `$_POST` parameters with JSON strings (as shown below), I'm not sure whether this is considered good practice or not. It strikes me that you also have a choice of putting `tableid` and `clientid` in the JSON, too (e.g. `request={"tableid":1,"clientid":2,"orderitems":[1,2,3]}`). Or even make the whole thing JSON (e.g. a `Content-Type` of `application/json`). I'm not sure what best practice is here. Perhaps others have insights here. It feels strange to have a mix of a bunch of standard `$_POST` variables and JSON, but as you can see below, it works. – Rob Aug 24 '13 at 03:51

1 Answers1

0

You ask:

Is it possible to POST both JSON-Objects and non-JSON Objects at the same time?

How would a valid request query look like? (I am using the Google Chrome App "Postman - REST Client" to test the queries) So what would the parameters look like if a wanted to pass tableid = 1, clientid = 1 and json = {1,2,3,4}?

Yes, you can post both JSON and non-JSON in a single request. The JSON {1,2,3} doesn't make sense, though. If it is a simple array, that would be [1,2,3]:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *messageBody = @"function=addOrder&tableid=1&clientid=2&json=[1,2,3]";
NSData   *messageData = [messageBody dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:messageData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error)
        NSLog(@"sendAsynchronousRequest error: %@", error);
    if (data) {
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
    }
}];

Note, in your while loop, you refer to $oitem['id'], but I don't understand this id you're referring to. Given that $orderitems is a simple array, each item is referenced by $oitem alone, (no ['id']).

And, as an aside, I generally use the foreach syntax:

foreach ($orderitems as $oitem) {
    // now I can refer to $oitem
}

If your JSON was [{"id":1},{"id":2},{"id":3}], then you'd refer to $oitem['id'], but if it's [1,2,3], you just refer to $oitem.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • 1
    Thank you so much for this excellent answer! It helped me a lot to better understand the whole topic. I changed my Objective-C code as well as my PHP-Code (it turned out, that there was also a problem with the SQL insert part). Now, the code is much clearer to me and I'm not that confused anymore. (Unfortunately I can not upvote your answer, since I have too low reputation yet, but I marked it as the accepted answer). Thank you! – Crumble Aug 25 '13 at 21:23