9

I'm trying to post some info to my PHP file from Swift. My php file is executed, but the posted variables just don't get through to the php file. What am I doing wrong?

Swift code:

@IBAction func buttonPress(sender: AnyObject) {

        let request = NSMutableURLRequest(URL: NSURL(string: "http://www.domain.com/php_swift_test/insert.php")!)
        request.HTTPMethod = "POST"

        let postString = "a=test&b=bla"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

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

            print("response = \(response)")

            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")
        }
        task.resume()
    }

PHP code:

<?php
    @session_start();
    @ob_start();

    $host='localhost';
    $user='test';
    $password='Passw0rd99';
    $db_name="mysql_test"; 

    $connection = mysql_connect($host,$user,$password);

    $a = $_POST['a'];
    $b = $_POST['b'];

    if(!$connection){
        die('Connection Failed');
    }
    else{
        $dbconnect = @mysql_select_db($db_name, $connection);

        if(!$dbconnect){
            die('Could not connect to Database');
        }
        else{
            $query = "INSERT INTO res_club (FirstName, LastName) VALUES ('$a','$b')";
            mysql_query($query, $connection) or die(mysql_error());

            echo 'Successfully added.';
            echo $query;
            echo $a.$b;
        }
    }
?>

An empty row is added to the database, with no first name and last name. The PHP file doesn't get the $_Post['a'] and b

The echo statement, echo $a.$b stays blank too. No errors are shown.

FireAlarm
  • 92
  • 1
  • 6
Martin Vidic
  • 135
  • 1
  • 1
  • 7
  • Are you getting an error? If so, show us what the error was and/or what the `responseString` was. That will help diagnose basic problems. Perhaps you can share the PHP code, as the problem may rest there (e.g. is it really looking for `application/x-www-formurlencoded` request). BTW, did you set the `NSAppTransportSecurity` in your `info.plist`? http://stackoverflow.com/questions/31254725/transport-security-has-blocked-a-cleartext-http/31254874#31254874. You might also want to set the `Content-Type` header, though that's not generally strictly required. – Rob May 23 '16 at 21:29
  • No errors shown. i added my php code above.... into.plist and content type. Are these things i would do in Xcode? or on the server? – Martin Vidic May 23 '16 at 22:34
  • But you do see the "responseString" message, which presumably shows "Successfully added" message and your `$query`? Also, when you print `response`, are you seeing a status code of 200? Re `info.plist` change, I'm surprised that it works at all if you used `http://` scheme on iOS 9 (if you have `https://`, though, it's not needed). But that can't be the problem because that would have resulted in an error message. – Rob May 24 '16 at 00:08
  • Thanx :) That was actually it... In xcode i had http whereas on my server I rewrite to https. So I changed my Xcode urls to https and now it works. – Martin Vidic May 24 '16 at 17:22

2 Answers2

6

This worked for me.

Video - https://youtu.be/wYkZ47Rz8iU

Swift Code - Example

let request = NSMutableURLRequest(URL: NSURL(string: "http://www.kandidlabs.com/YouTube/SwiftToMySQL/insert.php")!)
        request.HTTPMethod = "POST"
        let postString = "a=\(usernametext.text!)&b=\(password.text!)&c=\(info.text!)&d=\(number.text!)"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

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

            print("response = \(response)")

            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")
        }
        task.resume()

PHP Code - Example

 <?php
    $host='localhost';
    $user='root';
    $password='';

    $connection = mysql_connect($host,$user,$password);

    $usernmae = $_POST['a'];
    $pass = $_POST['b'];
    $info = $_POST['c'];
    $num = $_POST['d'];

    if(!$connection)
    {
        die('Connection Failed');
    }
    else
    {
        $dbconnect = @mysql_select_db('YoutubeTutorialDB', $connection);

        if(!$dbconnect)
        {
            die('Could not connect to Database');
        }
        else
        {
            $query = "INSERT INTO `YoutubeTutorialDB`.`Users` (`Username`, `Password`, `Info`, `FavoriteNumber`)
                VALUES ('$username','$pass','$info','$num');";
            mysql_query($query, $connection) or die(mysql_error());

            echo 'Successfully added.';
            echo $query;
        }
    }
?>
cwilliamsz
  • 718
  • 9
  • 20
4

this is the updated version (swift 4) from the example above

// the only one that work
func sendJson(){
    let usernametext = "new person"
    let passwordtext = "nice"
    let request = NSMutableURLRequest(url: NSURL(string: "http://localhost/example/todatabase.php")! as URL)
    request.httpMethod = "POST"
    let postString = "Title=\(usernametext)&content=\(passwordtext)"
    request.httpBody = postString.data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request as 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("responseString = \(responseString)")
    }
    task.resume()
}

simply change the variable usernamtext,passwordtext or whatever inside the postString,and the url to your liking. this actually the only one that work i found that many other tutorial does not work.

  • Very nice. When printing responseString i get my output. But how do i place it into an array so i can access each value separately? – Wouter Feb 16 '19 at 22:15