从Swift将数据POST到PHP方法

时间:2016-05-23 21:11:14

标签: ios swift nsurlsession

我正在尝试将一些信息发布到Swift的PHP文件中。 我的php文件已执行,但发布的变量只是没有通过php文件。我做错了什么?

Swift代码:

@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代码:

<?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;
        }
    }
?>

数据库中添加了一个空行,没有名字和姓氏。 PHP文件没有获得$_Post['a']和b

echo语句echo $a.$b也保持空白。没有显示错误。

2 个答案:

答案 0 :(得分:4)

这对我有用。

视频 - https://youtu.be/wYkZ47Rz8iU

Swift Code - 示例

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代码 - 示例

 <?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;
        }
    }
?>

答案 1 :(得分:1)

这是上例中的更新版本(第4版)

// 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()
}

只需更改变量usernamtext,passwordtext或postString中的任何内容,以及您喜欢的URL。实际上,这是唯一可行的方法,我发现许多其他教程均无效。