views:

180

answers:

3

Hi everyone, I am developing iphone App using JSON framework, I am calling a PHP script to update MySQL database on local server. Using these code:

NSString *jsonString = [sendData JSONRepresentation];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString*post = [NSString stringWithFormat:@"&json=%@", jsonString];
NSData*postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];

[request setURL:[NSURL URLWithString:@"http://localhost:8888/update.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody:postData];

I would like to ask:

What is the PHP script to get data from that request, and how I can decode JSON data to PHP object to update to database? because I am newbie with PHP, sorry about my basic PHP question.

Any help would be appreciated.

Thank

+1  A: 

I haven't done this with the iPhone but looks like it will just be:

if(isset($_REQUEST['json']) && $_REQUEST['json']) {
    $jsonObj = json_decode($_REQUEST['json']);
    //mandatory sanitizing and verification here
    //PDO examples
    //$stmt = $db->prepare('INSERT ...');
    //$stmt->execute(array($jsonObj->userId, $jsonObj->specialData));
    //check statement execution
}

More info:

http://php.net/json_decode

http://php.net/pdo

Rob Olmos
A: 

Here are some lines of code with the limited info you provided

<?php
// get data
$rawJsonData = $_POST;
$decodedData = json_decode($rawJsonData);

// .. do some parsing on $decodedData ..

// save data
$db = new Db();
$db->insert('table', $decodedData);

The $decodedData will be a PHP array which you can process in any way you need and then save into db.

michal kralik
+1  A: 

You will find your data in the variable $_POST['json'], you can take a look at what you have received via POST by using:

<?php print_r($_POST); ?>

Once you have identified where is your data, you can pass from JSON to PHP data using:

<?php $phpObj = json_decode($_POST['json']); ?>

Again, you can use print_r to look at the structure of your data:

<?php print_r($phpObj); ?>
E. Avilés
Thank you, I did like you said and it worked perfectly.
haisergeant