我想问一下如何将数据从Xcode 8发布到PHP MySQL数据库中。现在我有 textField用户名和注册按钮来触发功能发布。
到目前为止,这是我的代码。
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 :(得分: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()