简体   繁体   English

每次我尝试使用Swift和Alamofire将数据发布到MySQL数据库时,数据是否显示为null?

[英]Every time I try to post data to MySQL database using Swift and Alamofire the data appears null?

func uploadPostData() {

    let parameters: [String: Any] =
        ["title": "\(titleName!)", // string
        "link": "\(link!)", // string
        "available_shares": sharesNum!, // int
        "risk": riskLevel!, // int
        "description": descriptionView.text!, // string
        "postID": postID, // string
        "price": 0.99,
        "timestamp": 700
        ]
    print(parameters)

    Alamofire.request("example.com", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: nil)
        .responseJSON() { response in
            switch response.result {



    }
}

Above is my Swift method that calls the PHP script, which I'll attach below. 上面是我的Swift方法,该方法调用了PHP脚本,下面将对此进行附加。 I believe the problem lies in my PHP, as the POST request was definitely received. 我相信问题出在我的PHP中,因为确实收到了POST请求。 My database actually does update when the method is called, but the data in all of the columns is null/a default value. 当调用该方法时,我的数据库实际上确实会更新,但是所有列中的数据均为null /默认值。 I tried printing out the parameters dictionary, but it appears completely as expected, with no null values. 我尝试打印出参数字典,但是它完全按预期显示,没有空值。

    <?php

    $item1 = $_POST['title'];
    $item2 = $_POST['link'];
    $item3 = $_POST['available_shares'];
    $item4 = $_POST['risk'];
    $item5 = $_POST['description'];
    $item6 = $_POST['postID'];
    $item7 = $_POST['price'];
    $item8 = $_POST['timestamp'];

// Create connection
    $mysqli=mysqli_connect("localhost","username","password","database"); 

// Check connection
    if (mysqli_connect_errno())
    {
      echo "
Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $query = "INSERT INTO `TB_POSTS` (postID, timestamp, link, price, title, available_shares, risk, description) VALUES ('".$item6."','.$item8.','".$item2."','".$item7."','".$item1."','".$item3."','".$item4."','".$item5.")";

    $result = mysqli_query($mysqli,$query);

    echo $result; // sends 1 if insert worked
?>

The bottom line, which outputs 1 if the insertion worked, surprisingly does work. 如果插入有效,则底线输出1,这确实令人惊讶。 But again, the problem seems to be that the updated data never actually appears in the database. 但是同样,问题似乎是更新的数据实际上从未出现在数据库中。 I know it is updating because there is one more row in the table, but the actual values are never present. 我知道它正在更新,因为表中还有一行,但是实际值永远不会出现。 I also got the Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength error when I used .responseJSON, but when I changed it to .responseString I would get an output of 'SUCCESS'. 当我使用.responseJSON时,我还遇到了Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength错误,但是当我将其更改为.responseString时,我会得到“ SUCCESS”的输出。 Thanks a lot to anyone who can help. 非常感谢任何可以提供帮助的人。

You should use parameterized queries to prevent sql injection. 您应该使用参数化查询来防止SQL注入。 Here is a link that you should read through and then bookmark so you have it for quick reference. 这是您应该通读然后添加书签的链接,以便快速参考。

https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection

I updated your code using parameterized queries as a model for you to examine. 我使用参数化查询作为模型来更新代码,以供您检查。

$item1 = $_POST['title'];
$item2 = $_POST['link'];
$item3 = $_POST['available_shares'];
$item4 = $_POST['risk'];
$item5 = $_POST['description'];
$item6 = $_POST['postID'];
$item7 = $_POST['price'];
$item8 = $_POST['timestamp'];

// Create connection
$mysqli=mysqli_connect("localhost","username","password","database"); 

// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$query = "INSERT INTO `TB_POSTS` 

(
  postID, 
  timestamp, 
  link, 
  price, 
  title, 
  available_shares, 
  risk, 
  description 

) VALUES(?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = $mysqli->prepare($query);  //Prepare
$stmt->bind_param("ssssssss", $item6, $item8, $item2, $item7, $item1, $item3, $item4, $item5);  //Bind
$stmt->execute();//Execute
if($stmt->affected_rows === 0) exit('Nothing was inserted.');  //Check to see if it worked
$stmt->close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM