Swift / MySQL / PHP'必需参数缺失'错误

时间:2021-08-15 19:53:12

Here is my swift for registering the user:

这是我注册用户的快捷方式:

//Information fields
@IBOutlet weak var user: UITextField!
@IBOutlet weak var pass: UITextField!
@IBOutlet weak var pass2: UITextField!
@IBOutlet weak var name: UITextField!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var Message: UILabel!


//Register button
@IBAction func register(_ sender: Any) {

    let Parameters = ["username": user.text, "password": pass.text, "email": email.text, "name": name.text]

    let url = URL(string: "http://cgi.soic.indiana.edu/~lvweiss/prof4/register.php")!

    let session = URLSession.shared

    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: Parameters, options: .prettyPrinted)
    } catch let error {
        print(error.localizedDescription)
        Message.text = String(error.localizedDescription)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print(json)
                }
        } catch let error {
            print(error.localizedDescription)
            self.Message.text = String(error.localizedDescription)
        }
    })
    task.resume()
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

Here is the PHP:

这是PHP:

<?php
require_once 'DbOperation.php';

$response = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!verifyRequiredParams(array('username', 'password', 'email', 'name'))) {
    //getting values
    $username = $_POST['username'];
    $password = $_POST['password'];
    $email = $_POST['email'];
    $name = $_POST['name'];

    //creating db operation object
    $db = new DbOperation();

    //adding user to database
    $result = $db->createUser($username, $password, $email, $name);

    //making the response accordingly
    if ($result == USER_CREATED) {
        $response['error'] = false;
        $response['message'] = 'User created successfully';
    } elseif ($result == USER_ALREADY_EXIST) {
        $response['error'] = true;
        $response['message'] = 'User already exist';
    } elseif ($result == USER_NOT_CREATED) {
        $response['error'] = true;
        $response['message'] = 'Some error occurred';
    }
} else {
    $response['error'] = true;
    $response['message'] = 'Required parameters are missing';
}
} else {
$response['error'] = true;
$response['message'] = 'Invalid request';
}

//function to validate the required parameter in request
function verifyRequiredParams($required_fields)
{

//Looping through all the parameters
foreach ($required_fields as $field) {
    //if any requred parameter is missing
    if (!isset($_POST[$field]) || strlen(trim($_POST[$field])) <= 0) {

        //returning true;
        return true;
    }
}
return false;
}

echo json_encode($response);
?>

Here is the information I am trying to post to the database: iOS Registration Fields:

以下是我尝试发布到数据库的信息:iOS注册字段:

Swift / MySQL / PHP'必需参数缺失'错误

And the error I am receiving from Xcode when hitting the register button:

以及我在点击注册按钮时从Xcode收到的错误:

2017-11-14 00:42:01.529344-0500 WeissProf4[8754:662299] [MC] Lazy loading NSBundle MobileCoreServices.framework
2017-11-14 00:42:01.530670-0500 WeissProf4[8754:662299] [MC] Loaded MobileCoreServices.framework
2017-11-14 00:42:01.550941-0500 WeissProf4[8754:662299] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/leviweiss/Library/Developer/CoreSimulator/Devices/C98EE410-1CA2-4B4B-9ED8-A4F112C629E2/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-11-14 00:42:03.468653-0500 WeissProf4[8754:662299] [MC] Reading from private effective user settings.
2017-11-14 00:42:04.769899-0500 WeissProf4[8754:662505] [MC] Invalidating cache
2017-11-14 00:42:05.281372-0500 WeissProf4[8754:662299] [MC] Reading from private effective user settings.
["message": Required parameters are missing, "error": 1]

2017-11-14 00:42:01.529344-0500 WeissProf4 [8754:662299] [MC]延迟加载NSBundle MobileCoreServices.framework 2017-11-14 00:42:01.530670-0500 WeissProf4 [8754:662299] [MC]已加载MobileCoreServices .framework 2017-11-14 00:42:01.550941-0500 WeissProf4 [8754:662299] [MC] systemgroup.com.apple.configurationprofiles路径的系统组容器是/ Users / leviweiss / Library / Developer / CoreSimulator / Devices / C98EE410 -1CA2-4B4B-9ED8-A4F112C629E2 / data / Containers / Shared / SystemGroup / systemgroup.com.apple.configurationprofiles 2017-11-14 00:42:03.468653-0500 WeissProf4 [8754:662299] [MC]从私人有效用户中读取设置。 2017-11-14 00:42:04.769899-0500 WeissProf4 [8754:662505] [MC]无效缓存2017-11-14 00:42:05.281372-0500 WeissProf4 [8754:662299] [MC]从私人有效用户设置读取。 [“message”:缺少必需参数,“错误”:1]

I'm not sure what is going on, I know the PHP is successfully connecting to the DB and is able to post the required info (tested with Postman). I am thinking it could be an error with how Swift deals with posting in PHP, although I am absolutely not a PHP expert.

我不确定发生了什么,我知道PHP已成功连接到数据库,并且能够发布所需信息(使用Postman测试)。我认为这可能是Swift如何处理PHP发布的错误,尽管我绝对不是PHP专家。

1 个解决方案

#1


0  

SOLUTION Swift4:

@IBAction func register(_ sender: Any) {

let request = NSMutableURLRequest(url: NSURL(string: "http://cgi.soic.indiana.edu/~lvweiss/prof4/register.php")! as URL)
request.httpMethod = "POST"
let postString = "username=\(user.text!)&password=\(pass.text!)&email=\(email.text!)&name=\(name.text!)"
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=\(String(describing: error))")
        return
    }

    print("response = \(String(describing: response))")

    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    print("responseString = \(String(describing: responseString))")
}
task.resume()

}

#1


0  

SOLUTION Swift4:

@IBAction func register(_ sender: Any) {

let request = NSMutableURLRequest(url: NSURL(string: "http://cgi.soic.indiana.edu/~lvweiss/prof4/register.php")! as URL)
request.httpMethod = "POST"
let postString = "username=\(user.text!)&password=\(pass.text!)&email=\(email.text!)&name=\(name.text!)"
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=\(String(describing: error))")
        return
    }

    print("response = \(String(describing: response))")

    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    print("responseString = \(String(describing: responseString))")
}
task.resume()

}