Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Correct approach to insert data into a mySql database

I have found some info here and here but I didn't find a tutorial or a good book regarding this matter.

I don't want to use Parse for many reasons so I have decided to try to code the webservice myself. (I hope this is the correct way to name it).

I bought different books and while it's very well explained how I should retrieve data from the database using JSON or XML, I can't find anything clear regarding the data insertion.

This is how I finally managed to insert my data from the iphone app to my database.

XCODE:

-(IBAction)addData:(id)sender{

[self displayActivityIndicator];

NSString *country = self.countryLabel.text;
NSString *location = self.locationTextField.text;
NSString *city = self.cityTextField.text;
NSString *distance = self.distanceTextField.text;
NSString *max_part = self.partcipantsTextField.text;
NSString *pace = self.paceField.text;

NSString *rawStr = [NSString stringWithFormat:@"country=%@&location=%@&&city=%@&distance=%@&pace=%@&partecipant=%@", country,
                    location,
                    city,
                    distance,
                    pace,max_part];

NSData *data = [rawStr dataUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:@"http://www.mywebsite.com/savedata.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(@"%@", responseString);

NSString *success = @"success";
[success dataUsingEncoding:NSUTF8StringEncoding];

NSLog(@"%lu", (unsigned long)responseString.length);
NSLog(@"%lu", (unsigned long)success.length);



[self dismissViewControllerAnimated:YES completion:nil]; // Dismiss the viewController upon success

}

SAVEDATA.PHP

<?php 
header('Content-type: text/plain; charset=utf-8');


$db_conn = new  PDO('mysql:host=localhost;dbname=mydatabase','admin','password');
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$message = "";
$user = @"testUser";
$country = ($_POST['country']); 
$city = ($_POST['city']);
$location = ($_POST['location']);
$distance = ($_POST['distance']);
$pace = ($_POST['pace']);
$part = ($_POST['partecipant']);

$qry = $db_conn->prepare('INSERT INTO  myTable(`user_id`,`country`,`city`,`location`,`distance`,`pace`,`max_number`) VALUES (:user,:country,:city,:location,:distance,:pace,:max_number)');
$qry->bindParam(':user', $user);
$qry->bindParam(':country', $country);
$qry->bindParam(':city', $city);
$qry->bindParam(':location', $location);
$qry->bindParam(':distance', $distance);
$qry->bindParam(':pace', $pace);
$qry->bindParam(':max_number', $part);
$qry->execute();

if ($qry) { $message = "success"; }
else { $message = "failed"; }

echo utf8_encode($message);
?>

The code above works and I am able to insert my data in the database.

  1. is this the correct approach to send data from the iOS device to the database?
  2. Do you know any good tutorial or book that explains clearly how to do this?
  3. how can I prevent some malicious user to insert "fake data" directly from the server doing something like this: http://www.mywebsite.com/savedata.php?country=fakeCountry&location= fakeLocation&city=fakeCity&distance=fakeDistance&partecipant=fakePartecipant
  4. Do I prevent sql Injection using PDO and prepare statements?

Thanks in Advance for your time.

like image 557
Mat Avatar asked Oct 30 '13 08:10

Mat


1 Answers

There is nothing wrong with the way you are inserting the data. I do it all the time.

Think of your PHP file as a very simple web service.

What you should do though is protect the PHP script from being run by anything else other than the procedure in your IOS app. There are a few things you can do. Pass a post parametre with some kind of identification from your app, check the user agent. I always pass an app version number as well, that way you can make sure your script remains backward compatible.

Good practice would be to make sure the your $_POST variables are set. Make sure the data you are posting in the IOS app isnt going to fail either. Check for html entities etc.

Hope this helps.

like image 177
Dylan Franklin Avatar answered Oct 03 '22 13:10

Dylan Franklin