dongzhun8449 2018-12-02 18:08
浏览 83
已采纳

PHP没有从Swift接收POST数据

I'm trying to write to a database and not able to get POST data from Swift into PHP. I've checked everything along the way and the data is present in request.httpBody before sending the request, but I get this error "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'order_id' cannot be null"

Also PHP prints an empty array of $request

Any help is appreciated. Racking my brain on this one! Here's the code

SWIFT:

    func saveNewProduct(product: ProductClass) {

    //declare parameter as a dictionary which contains string as key and value combination.
    let productDict: [String:Any] = ["order_id": product.order_id!,
                                     "product_sku": product.product_sku!,
                                     "product_description": product.product_description!,
                                     "product_base_price": product.product_base_price!,
                                     "product_price": product.product_price!,
                                     "product_min_qty": product.product_min_qty!,
                                     "product_qty": product.product_qty!,
                                     "product_subtotal": product.product_subtotal!,
                                     "product_imageURL": product.product_imageURL!]

    let urlString: String = "https://www.mywebsite.com/dbinsertproduct.php"
    guard let url = URL(string: urlString) else {
        print("Error: cannot create URL")
        return
    }

    //create the session object
    let session = URLSession.shared

    //create the URLRequest object using the url object
    var request = URLRequest(url: url)
    //set http method as POST
    request.httpMethod = "POST"

    do {
        request.httpBody = try? JSONSerialization.data(withJSONObject: productDict, options: .prettyPrinted)
    } catch let error {
        print(error.localizedDescription)
    }

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

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

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print(json)
                // handle json...
            }
        } catch let error {
            print(error.localizedDescription)
        }
    })
    task.resume()
}

PHP:

    <?php include("dbclass.php"); ?>

    <?php
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata, true);

    $newProduct = new DBConnector('mysql.mysite.com', 'username', 'password', 'mysiteorders');
    $p = $newProduct->dbInsertProduct($request);

    error_log($p);
    echo ($p);
    ?>

More PHP:

    public function dbInsertProduct($request)
    {

          try {

            $stmt = $this->prepare("INSERT INTO `products` (`order_id`,`product_sku`,`product_description`,`product_base_price`,`product_price`,`product_notes`,`product_min_qty`,`product_qty`,`product_subtotal`,`product_imageURL`) VALUES (:order_id,:product_sku,:product_description,:product_base_price,:product_price,:product_notes,:product_min_qty,:product_qty,:product_subtotal,:product_imageURL);");

            $stmt->bindParam(':order_id', $request['order_id']);
            $stmt->bindParam(':product_sku', $request['product_sku']);
            $stmt->bindParam(':product_description', $request['product_description']);
            $stmt->bindParam(':product_base_price', $request['product_base_price']);
            $stmt->bindParam(':product_price', $request['product_price']);
            $stmt->bindParam(':product_notes', $request['product_notes']);
            $stmt->bindParam(':product_min_qty', $request['product_min_qty']);
            $stmt->bindParam(':product_qty', $request['product_qty']);
            $stmt->bindParam(':product_subtotal', $request['product_subtotal']);
            $stmt->bindParam(':product_imageURL', $request['product_imageURL']);

            error_log( print_r($request, TRUE) );

            $stmt->execute();

          } catch(PDOException $e) {
            error_log($e->getMessage());
            echo json_encode($e->getMessage());
          }
      }

UPDATE:

The request shows up as GET, not POST (verified with Charles proxy). As you can see in the code, I'm setting request.httpMethod = "POST". Am I missing something else??

  • 写回答

1条回答 默认 最新

  • douchensou6495 2018-12-09 04:48
    关注

    I found that the POST was being changed to GET upon redirect from www.mysite.com to mysite.com. Removing the 'www' did the trick.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题