2

I have a problem on Xcode using Swift 3.0, i want to store information in a mysql database with php. The php code is reached but always return failure on the insert request. I don't know, it works fine with android. Here's my code :

Swift :

@IBAction func SignUp(_ sender: UIButton) {
    var Name1: String = Name.text!
    var Prenom: String = PRENAME.text!
    var add: String = Addr.text!
    var code:String = CP.text!
    var mail:String = Email.text!
    var pass:String = password.text!


    var request = URLRequest(url: URL(string: "http://www.example.com/myscript.php")!)
    request.httpMethod = "POST"
    let postString = "name=\(Name1)&pname=\(Prenom)&add=\(add)&pc=\(code)&mail=\(mail)&pass=\(pass)"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString)")
    }
    task.resume()
}

And my PHP code :

<?php

$reponse = array();



$pseudo = $_POST['name'];
$score = $_POST['pname'];
$add =  $_POST['add'];
$pc = $_POST['pc'];
$mail = $_POST['mail'];
$password = $_POST['pass'];
$mysqli = new MySQLi("host","root","pass","user");

$result = $mysqli->query("INSERT INTO compte (Name,Name2,Ad,code,maiil,pass) VALUES('$pseudo','$score','$add','$pc','$mail','$password')");
if ($mysqli->connect_error){
    die('Connect Error (' . $mysqli->connect_errno . ') '
        . $mysqli->connect_error);
}
if($result){

    $response["success"] = 1;
    $response["message"] = "SUCCESS!";

    echo json_encode($response);
}
else{
    $response["success"] = 0;
    $response["message"] = "FAILURE!";

    echo json_encode($response);
}
  • The application does not tell me what the problem is and the thing is sometimes the insertion in the database work but sometimes not. So i'm completely lost... – Adam Harmand Dec 23 '17 at 14:59
  • On failure, you the query, you're not returning the error code, so you're flying blind. I'd suggest returning `$mysqli->error` instead of just `"FAILURE!"`, so you can see why it failed. Also, the test for the failed connection should go _before_ you perform the query. – Rob Dec 23 '17 at 15:15
  • Thank you so much ! I have forgotten that i don't let duplicate the mail in my database, everything is fine, it works perfectly, thanks ! – Adam Harmand Dec 23 '17 at 15:22
  • Yes you're right i have to change my php code – Adam Harmand Dec 23 '17 at 15:29
  • You have a spelling mistake in your insert, maiil
    `(Name,Name2,Ad,code,maiil,pass)`
    – halojoy Dec 23 '17 at 14:58
  • Dude, i tell it in the post that, it works fine in my Android device, so it can't be an error of typing. – Adam Harmand Dec 23 '17 at 15:01

3 Answers3

0

don't forget to add this to info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

so you can fire http or https requests

-- make sure any of you parameters don't contain & so value can be sent successfully or replace it with %26

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

Sorry, my bad everything is OK, by doing the sqli->error, i have found the error, i have forgotten that i don't let duplicate the mail in my database. So thank you very much everyone. And have a good week end !

0

A couple of thoughts:

  1. On failure, you should set message to $mysqli->error instead of just "FAILURE!", so you can see why it failed.

  2. I'd suggest moving the "did connection fail" logic before you attempt the query. I'd also suggest you change this to output JSON that says that the connection failed and exit, rather than just performing die. Later, as you improve the Swift code to parse errors, it will be useful to keep all server messages as JSON.

  3. You should change the PHP to escape the parameters using real_escape_string. In the absence of that, if any of your values included a ' character, your SQL will fail. (You're also susceptible to SQL injection attacks.)

  4. You should change the Swift to percent escape the values included in the httpBody of the request. See https://stackoverflow.com/a/28027627/1271826 for examples. Or use something like Alamofire that takes care of this for you. But as it stands:

    • If any of these values included a + character, it would likely be replaced with a space.

    • If any of these values included a & character, it would end up truncating that field.

    • If any of these values included any other reserved character, the whole query could fail.

  5. While not essential, I'd suggest :

    • In the Swift code, set the Content-Type header of the request to application/x-www-form-urlencoded and the Accept header of the request to application/json.

      request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
      request.setValue("application/json", forHTTPHeaderField: "Accept")
      
    • In the PHP code, set the Content-Type header to application/json before you echo the JSON:

      header("Content-Type: application/json");
      

      While this is optional, if you later adopt a library, like Alamofire, which performs validation for these standard headers, it will make your life easier.

Rob
  • 415,655
  • 72
  • 787
  • 1,044