2016-12-29 185 views
0

我想問一下如何將數據從Xcode 8發佈到PHP MySQL數據庫中。現在我有textField用戶名註冊按鈕觸發功能帖子。如何將數據從Xcode 8發送到PHP MySQL數據庫?

這是我的代碼到目前爲止。

registerVC.swift

import UIKit 
class RegisterVC: UIViewController { 
    @IBOutlet var usernametxt: UITextField! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

    @IBAction func register_click(_ sender: Any) { 

     if usernametxt.text!.isEmpty{ 
      usernametxt.attributedPlaceholder = NSAttributedString(string: "username", attributes: [NSForegroundColorAttributeName: UIColor.red]) 
     } 

     else{ 
      // Insert data into database 
     } 
    } 
} 

Register.php

<?php 
    $connect  = mysqli_connect("", "", "", ""); 
    global $connect; 
    if(isset($_POST['username'])) 
    { 
     $username  = $_POST['username']; 
     $insert   = "INSERT INTO table (username) 
            VALUES ('$username')"; 
     $run   = mysqli_query($connect,$insert); 

     $response = array(); 
     $response["success"] = true; 
     echo json_encode($response); 
    } 
?> 

回答

0

在你else添加sendData(usernametxt.text) 並在VC文件中添加以下功能

func sendData(username : String) { 
    var request = URLRequest(url: URL(string:"http://YOUR_WEBPAGE_ADDRESS")!) 
    request.httpMethod = "POST" 
    let postString = "name="+username 
    request.httpBody = postString.data(using: .utf8) 
    let task = URLSession.shared.dataTask(with: request) { data, response, error in 
    guard let data = data, error == nil else {            
     print("error=\(error)") 
     return 
    } 
    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
     print("statusCode should be 200, but is \(httpStatus.statusCode)") 
     print("response = \(response)") 
    } 

    let responseString = String(data: data, encoding: .utf8) 
    print("responseString = \(responseString)") 
    } 
} 
task.resume() 
+0

「讓任務」出錯。它說永遠不會使用不可變值'任務'的初始化 – Jamilah

+0

在末尾添加'task.resume()' –

+0

我認爲它的工作原理,因爲當我嘗試構建它時沒有錯誤出現。但是錯誤「ssl證書握手失敗」。你有這個問題的解決方案嗎?謝謝 。 .. – Jamilah

相關問題