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:
Is this valid php-Code?
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}?
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);
}
}
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
.