基于ID字段插入多个数据库表,只有第一个表插入工作

时间:2018-02-09 11:31:56

标签: php ios mysql sql swift

我对Swift开发很新,并且一直在使用一些教程来使用我的API来实现这一点,我只是不确定为什么第二个语句不能与swift一起使用时它似乎在使用POSTMAN的测试中正常工作。这在POSTMAN上测试时工作正常,但只插入到logIn表中,第二个插件仅适用于postman而不是在Swift中在模拟器上测试时 这是快速代码

`let URL_USER_REGISTER = "URLString"
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"

    let date = formatter.string(from: dob.date)
    print(date)
    //send parameters
    let parameters: Parameters=[
        "username":usernameTextField.text!,
        "password":passwordTextField.text!,
        "trainer": trainer,
        "first": firstNameTextField.text!,
        "surname": surnameTextField.text!,
        "email": emailTextField.text!,
        "dob": date,
        "goal": goalTextField.text!,
        "weight": weightTextField.text!,
        "height": heightTextField.text!]

    //Sending http post request
    let headers = [
        "Content-Type": "application/x-www-form-urlencoded"
    ]
    Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters, encoding: URLEncoding()).responseJSON
        {
            response in
            //printing response
            print(response)
            //getting the json value from the server
            if let result = response.result.value {

//                    converting it as NSDictionary
                let jsonData = result as! NSDictionary

//                    displaying the message to user
                self.displayMessage(userMessage: (jsonData.value(forKey: "message") as! String?)!)

            }
    }
}`

和php文件

<?php

//importing required script
require_once '../includes/DbOperation.php';

$response = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyRequiredParams(array('username', 'password', 'trainer',         'first', 'surname', 'email', 'dob', 'goal', 'weight', 'height'))) {
    //getting values
    $username = $_POST['username'];
    $password = $_POST['password'];
    $trainer = $_POST['trainer'];
    $first = $_POST['first'];
    $surname = $_POST['surname'];
    $email = $_POST['email'];
    $dob = $_POST['dob'];
    $goal = $_POST['goal'];
    $weight = $_POST['weight'];
    $height = $_POST['height'];

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

    //adding user to database
    $result = $db->createUser($username, $password, $trainer, $first, $surname, $email, $dob, $goal, $weight, $height);

    //making the response accordingly
    if ($result == USER_CREATED) {
        $response['error'] = false;
        $response['message'] = 'Your account has been created';
    } elseif ($result == USER_ALREADY_EXIST) {
        $response['error'] = true;
        $response['message'] = 'User already exist. Please try again';
    } elseif ($result == USER_NOT_CREATED) {
        $response['error'] = true;
        $response['message'] = 'Sorry, your request could not be processed at this time.';
    }elseif ($result == LOGIN_CREATED_USER_NOT_CREATED){
        $response['error'] = true;
        $response['message'] = 'LogIn Created, Profile could not be created.';
    }
} else {
    $response['error'] = true;
    $response['message'] = 'Please enter all fields';
}
} else {
    $response['error'] = true;
    $response['message'] = 'Invalid request';
}

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

//Getting the request parameters
$request_params = $_REQUEST;

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

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

echo json_encode($response);


public function getUserByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT id, username, trainer FROM LogIn WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($id, $uname, $trainer);
    $stmt->fetch();
    $user = array();
    $user['id'] = $id;
    $user['username'] = $uname;
    $user['trainer'] = $trainer;
    return $user;
}

//Function to create a new user
public function createUser($username, $pass, $trainer, $firstName, $surname, $email, $dob, $goal, $weight, $height)
{
    if (!$this->isUserExist($username)) {
        $password = md5($pass);
        $stmt = $this->conn->prepare("INSERT INTO LogIn (username, password, trainer) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $username, $password, $trainer);

        if ($stmt->execute()) {

            $user = $this->getUserByUsername($username);
            //var_dump($user["id"]);
            $stmt2 = $this->conn->prepare("INSERT INTO Client(client_id, client_first_name, client_surname, client_email, client_dob, 
            client_goal, client_weight, client_height, number_of_cancellations)VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)");
            $stmt2->bind_param("ssssssss", $user["id"], $firstName, $surname, $email, $dob, $goal, $weight, $height);

            if ($stmt2->execute()){
                return USER_CREATED;
            }else {
                return LOGIN_CREATED_USER_NOT_CREATED;
            }
        } else {
            return USER_NOT_CREATED;
        }
    } else {
        return USER_ALREADY_EXIST;
    }
}


private function isUserExist($username)
{
    $stmt = $this->conn->prepare("SELECT id FROM LogIn WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();
    return $stmt->num_rows > 0;
}
}

我试过环顾四周,似乎无法找到我想要做的答案。应用程序能够与API进行良好的通信,然后与数据库进行通信,因为第一个插入工作正常。我认为错误与iOS应用程序发送的参数有关,因为它在POSTMAN中测试时正常工作

提前感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:0)

好的,所以我弄清楚出了什么问题。出于某种原因,错误与

有关
            if ($stmt2->execute()){
            return USER_CREATED;
        }else {
            return LOGIN_CREATED_USER_NOT_CREATED;
        }
PHP文件中的

。我用

替换了这个
                $stmt2->execute();

            return USER_CREATED;

现在数据被添加到两个表而不仅仅是LogIn表