14210

Blank data inserted into MYSQL database with iOS frontend

Question:

I'm creating an app which requires to insert a row into a mysql database (hosted online) however whenever i try to insert the data, the data is blank. there is nothing wrong with the php as my web front end works perfectly with the php script.

NSString *user = self.registerUsername.text; NSString *password = self.registerPassword.text; NSString *email = self.registerEmail.text; NSString *model = [NSString stringWithFormat:@"%@", [[UIDevice currentDevice] model]]; NSString *sysVer = [NSString stringWithFormat:@"%@", [[UIDevice currentDevice] systemVersion]]; NSString *connectionURL = @"mydomain.com/Register.php"; NSLog(@"%@", connectionURL); //this is logged correctly NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:connectionURL]]; [request setHTTPMethod:@"POST"]; NSString *insert = [[NSString alloc] initWithFormat:@"username=%@&password=%@&email=%@&model=%@&sysver=%@", user, password, email, model, sysVer]; NSLog(@"%@", insert); [request setHTTPBody:[insert dataUsingEncoding:NSASCIIStringEncoding]]; //This is also logged correctly, giving me the right format i would expect NSURLResponse *response; NSError *error; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]]; NSLog(@"%@", responseString); //The response string is also correct, but no data is inserted into the database NSString *success = @"success"; [success dataUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%lu", (unsigned long)responseString.length); NSLog(@"%lu", (unsigned long)success.length);

mRegister.php

<?php header('Content-type: text/plain; charset=utf-8'); include("config/dp.php"); //<- db connection $con = mysql_connect("127.0.0.1","user","pass"); if(! $con) { die('Connection Failed'.mysql_error()); } mysql_select_db("hk", $con); $message = ""; $username = ($_POST['username']); $password = ($_POST['password']); $email = ($_POST['email']); $model = ($_POST['model']); $sysver = ($_POST['sysver']); $submit = $_POST["registerform"]; $sql = "INSERT INTO members (`username`, `password`, `email`, `model`, `sysver`) VALUES ('$username', '$password', '$email', '$model', '$sysver')"; $result = mysql_query($sql); $row = mysql_fetch_array($result); if ($result) { $message = "success"; } else { $message = "failed"; } echo utf8_encode($message); ?>

also, responseString usually shows up with some weird characters after it therefore affect the responseString.length value. Is there something wrong with my code or is it to do with my php?

Answer1:

Maybe PHP is not parsing the request body because you haven't set the Content-Type request header:

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

On the other hand I recommend you to use an HTTP library of iOS such as <a href="http://afnetworking.com" rel="nofollow">AFNetworking</a> so you don't have to worry about generating the request body by hand. Check out <a href="http://cocoadocs.org/docsets/AFNetworking/2.0.0/" rel="nofollow">its documentation</a>.

Recommend

  • Objective-C: Help needed to understand why two methods react differently when accessing a UIView in
  • Upload image to server ios
  • Calling web services with the help of AFNetworking in Objective C
  • NSString to NSData conversion to Hex Value [duplicate]
  • Objective C Methods and syntax
  • ios - App crashes when InApp mail command gets called
  • My Thread Programs Block
  • How to upload photos on twitter in iPhone?
  • ios - App crashes when InApp mail command gets called
  • LinkedIn Integration r_network and w_messages request not working together in iOS sdk
  • EXC_BAD_ACCESS error
  • POST with swift 2 on UIWebView does not work
  • iPhone : upload image to web aspx file
  • Making NSString global to whole project iPhone
  • Sending multipart request from iPhone to Ruby on Rails (RoR) server
  • UIWebview check if user is logged in and return True or False
  • Swift parse html table
  • iOS 5- sending json using NSURLRequest and parsing in php via $_POST
  • How to load HTML in UITextView?
  • Refresh tableview after delete a tableview cell and refresh view controller
  • Prevent redirect response with Alamofire in Swift
  • HTTP status code = 0 (iPhone) (objective c)
  • MongoError: Incorrect arguments
  • Django rest serializer Breaks when data exists
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • JSON with duplicate key names losing information when parsed
  • Can I have the cursor start on a particular column by default in jqgrid's edit mode?
  • How to limit post in wp_query
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Circular dependency while pushing http interceptor
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • Linker errors when using intrinsic function via function pointer
  • AngularJs get employee from factory
  • Codeigniter doesn't let me update entry, because some fields must be unique
  • Free memory of cv::Mat loaded using FileStorage API
  • Getting error when using KSoap library to consume .NET web services
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Memory offsets in inline assembly
  • Turn off referential integrity in Derby? is it possible?
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize