我正在尝试将数据发送到php并将其插入到mysql数据库中,但它似乎无法正常工作。我已经尝试将数据发送到php只是为了将其编码为json并将其回送给swift并返回结果,这意味着php文件接收到数据。但是插入数据不起作用。
swift2 httppost
func post() {
let myUrl = NSURL(string: "http://localhost:8080/json/json.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST"
// Compose a query string
let postString = "firstName=James&lastName=Bond";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
//Let’s convert response sent from a server side script to a NSDictionary object:
do{
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
if let parseJSON = myJSON {
// Now we can access value of First Name by its key
let firstNameValue = parseJSON["firstName"] as? String
print("firstNameValue: \(firstNameValue)")
}
}catch let error as NSError {
print("JSON Error: \(error.localizedDescription)")
}
}
task.resume()
}
json.php
<?php
// Read request parameters
$firstName= $_REQUEST["firstName"];
$lastName = $_REQUEST["lastName"];// Store values in an array
$conn = mysqli("localhost", "root", "root", "notify");
$query = mysqli_query($conn, "INSERT INTO user values('', '$firstName',
'$lastName')");
?>
答案 0 :(得分:1)
如果服务器只是回应请求工作,那么问题在于服务器,而不是客户端代码。我建议在PHP代码中添加一些错误处理:
<?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);
?>
注意:
我不建议以root
登录。
确保使用mysqli_real_escape_string
来保护自己免受SQL注入攻击(参见第1点)。
我不知道您的user
表中是否包含其他字段,但如果是,则可能需要在insert
语句中指定列名。即使您只有这两列,也是一种“面向未来”代码的好方法。
注意,我已将此更改为生成JSON响应。我这样做是因为它使客户端代码更容易解析和处理响应。我会将NSJSONSerialization
留给您。