使用swift2插入数据库

时间:2016-04-04 04:30:13

标签: php mysql database xcode swift2

所以我使用swift 2开发应用程序。我有一个关于phpmyadmin的数据库,我正在使用MAMP进行托管(所以在本地)。我正在尝试为我的应用创建一个简单的注册页面,因此一旦用户输入用户名和密码,它应该将其存储到我的数据库中。我的数据库名为userAccounts,该表称为users。它有两列:用户名和密码。我已经在我的swift文件和php文件中编写了代码,但它没有插入到我的数据库中。我还没找到原因。

这是swift文件:

@IBOutlet var usernameTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

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

@IBAction func pressButton(sender: AnyObject) {
    let request = NSMutableURLRequest(URL: NSURL(string: "file:///Applications/MAMP/htdocs/userInsert.php")!)
    request.HTTPMethod = "POST"
    let postString = "a=\(usernameTextField.text!)&b=\(passwordTextField.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文件:

$user = 'x';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;

$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'@'localhost'");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

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

$sql = "INSERT INTO `userAccounts`.`users` (`username`, `password`)
            VALUES ('$username','$password')";
$result = mysqli_query($link, $sql);

echo "inserted into database Successfully"
mysqli_close($link);

}
else {
    die('comment is not set or not containing valid value');
}

当我运行我的应用程序时,在控制台中打印出我的整个php文件,并没有在我的数据库中插入任何内容。知道我可能做错了吗?

1 个答案:

答案 0 :(得分:0)

从以下位置更改NSMutableURLRequest的初始化:

let request = NSMutableURLRequest(URL: NSURL(string: "file:///Applications/MAMP/htdocs/userInsert.php")!)

为:

let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost/userInsert.php")!)