且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift httppost数据未插入MySQL数据库

更新时间:2022-12-11 19:23:46

如果让服务器只是响应请求,那么问题就出在服务器内部,而不是客户端代码.我建议在PHP代码中添加一些错误处理:

If having the server just echo the request works, then the problem rests within the server, not the client code. I would suggest adding some error handling in the PHP code:

<?php

// specify that this will return JSON

header('Content-type: application/json');

// open database

$con = mysqli_connect("localhost","user","password","notify");

// Check connection

if (mysqli_connect_errno()) {
    echo json_encode(array("success" => false, "message" => mysqli_connect_error(), "sqlerrno" => mysqli_connect_errno()));
    exit;
}

// get the parameters

$field1 = mysqli_real_escape_string($con, $_REQUEST["firstName"]);
$field2 = mysqli_real_escape_string($con, $_REQUEST["lastName"]);

// perform the insert

$sql = "INSERT INTO user (first_name, last_name) VALUES ('{$field1}', '{$field2}')";

if (!mysqli_query($con, $sql)) {
    $response = array("success" => false, "message" => mysqli_error($con), "sqlerrno" => mysqli_errno($con), "sqlstate" => mysqli_sqlstate($con));
} else {
    $response = array("success" => true);
}

echo json_encode($response);

mysqli_close($con);

?>

注意:

  1. 我不建议以root身份登录.

确保使用mysqli_real_escape_string保护自己免受SQL注入攻击(请参阅第1点).

Make sure you use mysqli_real_escape_string to protect yourself against SQL injection attacks (see point 1).

我不知道您的user表中是否还有其他字段,但是如果这样,您可能要在insert语句中指定列名.即使只有这两列,这也是确保代码永不过时"的好方法.

I don't know if your user table has other fields in it, but if so, you might want to specify the column names in the insert statement. Even if you only have those two columns, it's a good way to "future-proof" your code.

注意,我已对此进行了更改以生成JSON响应.我这样做是因为它使客户端代码更容易解​​析和处理响应.我将NSJSONSerialization留给您.

Note, I've changed this to generate JSON response. I do that because it makes it easier for the client code to parse and handle the response. I'll leave the NSJSONSerialization to you.