I know this is a loaded question, but I think what I'm doing right now is probably the wrong way to go about things, so I'd like some input as to what is best practice.
Currently I have an array of actors. Let's say NSArray *actors
in Objective-C. I want to pass this up to my PHP page for storage.
Right now I pass this up on HTTP POST
by turning the array into a string such as this:
&actors=Joe Allen*Dave Smith*Mary Johnson*Alice Burg?movietitle=Runner
When it gets to PHP I'm then passing it to MySQL via a Stored Procedure call like this:
CALL Add_Movie(movietitle, actors);
And then in my sproc is where I 'explode' the actors by *
to save them in the correct table. I do the reverse to get the actors back. It's gotten even trickier for me when I've wanted to separate first/last names.
Anyway, this seems really hacky to me. What's best practice for an array transfer over HTTP to SQL storage and back?
That said, there are two standout candidate formats:
In the big picture what you've described sounds like the exact case for defining an REST API.
I would typically serialise 'plain-old' objects to JSON (iOS side), post the JSON and php side, decode the JSON. I wrote a category for dictionaries as follows ( you can use this as template for an NSArray+JSON category, should be almost identical).
NSDictionary+JSON.h :
#import <Foundation/Foundation.h>
@interface NSDictionary (JSON)
+(id) dictionaryWithJSONdata:(NSData*)jsonData;
+(id) dictionaryWithJSON:(NSString*)jsonString;
-(NSData*) asJSONdata;
-(NSString*) asJSON;
@end
NSDictionary+JSON.m :
@implementation NSDictionary (JSON)
+ (id)dictionaryWithJSONdata:(NSData *)jsonData {
NSError *error;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if (error) {
MPLOG(@"*** Error encountered while deserializing JSON from server : %@", error.description);
}
return dic;
}
+ (id)dictionaryWithJSON:(NSString *)jsonString {
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
return [NSDictionary dictionaryWithJSONdata:data];
}
- (NSData *)asJSONdata {
NSError *error;
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:self
options:NSJSONWritingPrettyPrinted
error:&error];
if (error) {
MPLOG(@"*** Error while converting to JSON data : %@", error.localizedDescription);
return nil;
} else {
return jsonData;
}
}
- (NSString *)asJSON {
NSData *jsonData = [self asJSONdata];
if (!jsonData) {
return @"{}";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
php side :
$content = file_get_contents('php://input');
$ary = json_decode($content , false); // false means as stdObj as opposed to array
edit : MPLOG is a personal logging framework, you should substitute for NSLog or whatever you currently use.
A common practice is to use JSON. It's how you encode data for REST API.
But you can do whatever you like. The most important is you are able to get data.