skip to Main Content

To preface, I’m currently still learning Swift and just wanted to have a dabble at trying to send data to some kind of backend from within my app.
Not sure if important but if so:

  • I am using fast comet as a web server with a PHPMyAdmin database in SQL. (struggling to get my head around it so that may be said incorrectly, apologies in advance!)

From what I can gather (please say if I’ve got this backwards), the executions on the database are written in SQL which I have included in my fetch request for my app (working successfully). The PHP file acts as a bridge to open a connection between the database and my end.

I’ve tried (semi-successfully) for 3 days to write a POST request in swift that will send the data from my app and insert it into my database. When I say semi-successfully, I mean that when triggering the inert method in my swift code from the app, data DOES get inserted into the database but it is the data on the alternative side of the nil-coalescing operator and not my data. This leads me to believe that all is (just about) okay with my .PHP file and that there is either a problem with my swift code, or that I’ve not set something up correctly within the database itself?

database with table named "Students" – consists of 5 fields:

  • id : INT
  • first_name : TEXT
  • last_name : TEXT
  • subject : TEXT
  • grade : INT

swift – what I’m trying to insert into the database:

  • id : Int
  • firstName : String
  • lastName : String
  • subject : String
  • grade : Int

swift code:

func postRequest(id: Int, firstName: String, lastName: String, subject: String, grade: Int, completion: @escaping (Error?) -> ()) {
    let insertGradesURL = URL(string: "http://kysodev.com/classroomGrades/insertClassroomGrades.php")!
    var urlRequest = URLRequest(url: insertGradesURL)
    urlRequest.httpMethod = "POST"
    
    let postString = "id=(id)&firstName=(firstName)&lastName=(lastName)&subject=(subject)&grade=(grade)"
    urlRequest.httpBody = postString.data(using: .utf8)
    
    let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
        if error != nil {
            print("error = (error)")
            return
        }
        print("response - (response)")
        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("response string - (responseString)")
    }
    task.resume()
    
}

I get no errors returned back from this but the response in the debugger:

response - Optional(<NSHTTPURLResponse: 0x280526f80> { URL: http://kysodev.com/classroomGrades/insertClassroomGrades.php } { Status Code: 200, Headers {
Connection =     (
    "Upgrade, Keep-Alive"
);
"Content-Encoding" =     (
    gzip
);
"Content-Type" =     (
    "text/html; charset=UTF-8"
);
Date =     (
    "Mon, 15 Mar 2021 16:37:33 GMT"
);
"Keep-Alive" =     (
    "timeout=5, max=100"
);
Server =     (
    Apache
);
"Transfer-Encoding" =     (
    Identity
);
Upgrade =     (
    "h2,h2c"
);
Vary =     (
    "Accept-Encoding"
);
"X-Powered-By" =     (
    "PHP/7.2.34"
);

} })

insertClassroomGrades.php file:

    <?php
$connection=mysqli_connect("localhost","knockyou_seb","*******","knockyou_classroomGrades");

if ($connection->connect_error) {
    error_log ("not connected to db");
  die("Connection failed: " . $conn->connect_error);
} else {
    
    $id = $_POST['id'] ?? 13;
    $firstName = $_POST['firstName'] ?? 'Test';
    $lastName = $_POST['lastName'] ?? 'McTest';
    $subject = $_POST['subject'] ?? 'Test Subject'; 
    $grade = $_POST['grade'] ?? 5;
    
    $sql = "INSERT INTO Students (id, first_name, last_name, subject, grade) VALUES ('".$id."','".$firstName."','".$lastName."','".$subject."','".$grade."');";
}

mysqli_close($connection);
?>

The php previously was allowing me to update the database with the example student, Test McTest, alas that’s now not working either and I’m not sure If I have some kind of timeout issue and if so how to resolve that or if its my swift code, or just a mix of everything!

I’ve made sure I’m not submitting duplicate id field values into the database as I’ve set that field as unique. I’ve also tried varying my swift code so that it sends the postString as String values but that hadn’t resolved it either.

If anyone could point me in the right direction I’d be very grateful, thank you.

2

Answers


  1. You are not executing your query in the PHP code, try to edit your code like this:

    <?php
    
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $connection = new mysqli("localhost", "knockyou_seb", "*******", "knockyou_classroomGrades");
    
    $id = $_POST['id'] ?? 13;
    $firstName = $_POST['firstName'] ?? 'Test';
    $lastName = $_POST['lastName'] ?? 'McTest';
    $subject = $_POST['subject'] ?? 'Test Subject';
    $grade = $_POST['grade'] ?? 5;
    
    $sql = $connection->prepare("INSERT INTO Students (id, first_name, last_name, subject, grade) VALUES (?, ?, ?, ?, ?)");
    $sql->bind_param("isssi", $id, $firstName, $lastName, $subject, $grade);
    $sql->execute();
    $sql->close();
    
    $connection->close();
    
    Login or Signup to reply.
  2. Two points of caution:

    1. When building application/x-www-form-urlencoded requests in Swift, you must percent encode the values. E.g. https://stackoverflow.com/a/41092318/1271826. If you send a post request with an unescaped reserved character (e.g. if there was a space in the “subject”), it will fail.

    2. Do not just insert values into SQL statement. You should bind the values to ? placeholders. See https://stackoverflow.com/a/59298729/1271826. If inserted a value with a ' character, you server code will fail. Plus you are opening yourself to SQL injection attacks.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search