Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

ios - POST data to a PHP method from Swift

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...