0

I'm new to Swift and I'm trying to make a simple app to put names in a MySQL database. When I run the Swift script in simulator, nothing changes in the database. What am I doing wrong?

Many thanks in advance!

Connect.php

//Connect to Database
$user="something_net_something";
$host="something.net.mysql";
$password="SecretPassword";
$database="something_net_something";
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
mysqli_select_db($connection,$database) or die ("couldn’t select database");

Function.php

header('Content-Type: text/html; charset=ISO-8859-1');
//Connect to Database
include "Connect.php";
//getting values
$fname = $_POST['Fname'];
$lname = $_POST['Lname'];
//query
$QRY="INSERT INTO oneiros_aether_personage (Fname, Lname) VALUES ($fname, $lname)";
if (mysqli_query($connection, $QRY)) {
    $response['error']=false;
    $response['message']="New record created successfully";
} else {
    $response['error']=true;
    $response['message']="Error: " . $QRY . "<br>" . mysqli_error($connection);
}
echo json_encode($response);
mysqli_close($connection);  

ViewController.swift

import UIKit

class ViewController: UIViewController {

//URL to our web service
let URL_ADD_PERSONAGE = "http://www.something.net/Function.php"


//TextFields declarations
@IBOutlet weak var textFieldFname: UITextField!
@IBOutlet weak var textFieldLname: UITextField!


//Button action method
@IBAction func buttonSave(sender: UIButton) {

    //created NSURL
    let requestURL = URL(string: URL_ADD_PERSONAGE)

    //creating NSMutableURLRequest
    let request = NSMutableURLRequest(url: requestURL! as URL)

    //setting the method to post
    request.httpMethod = "POST";

    //getting values from text fields
    let fname = textFieldFname.text
    let lname = textFieldLname.text

    //creating the post parameter by concatenating the keys and values from text field
    let postParameters = "Fname="+fname!+"&Lname="+lname!;

    //adding the parameters to request body
    request.httpBody = postParameters.data(using: String.Encoding.utf8)


    //creating a task to send the post request
    let task = URLSession.shared.dataTask(with:request as URLRequest){
        data, response, error in

        if error != nil{
            print("error is \(error)")
            return;
        }

        //parsing the response
        do {
            //converting resonse to NSDictionary
            let myJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            //parsing the json
            if let parseJSON = myJSON {

                //creating a string
                var msg : String!

                //getting the json response
                msg = parseJSON["message"] as! String?

                //printing the response
                print(msg)

            }
        } catch {
            print(error)
        }

    }
    //executing the task
    task.resume()

}


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

To Info.plist I added

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
2
  • 2
    Have you tried narrowing down the problem? What have you tried? Is there a problem with the SQL setup, php script, your app? Commented Jan 6, 2017 at 13:18
  • @milo526 in the Function.php I changed the $_POST[ ] with fixed strings and script added the strings to my database, so I assume somethings wrong in the swift code Commented Jan 6, 2017 at 13:22

1 Answer 1

2

your code works fine with me, check the URL_ADD_PERSONAGE variable, IBOutlet and others.

The connection logic has no error.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @wajeeh , I figgered it out, it was the IBAction. Removed it and I dragged it again from the Main to ViewController. Now it works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.