I am trying to send data to php and insert it to mysql database but it doesn't seem to work. I have tried sending data to php just to encode it to json and echo it back to swift and it returns a result so it means that the php file received the data. However inserting the data is not working.
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')");
?>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…