I'm creating a Swift POST Request to a MySQL web service after tapping in a button with some code. However, I am not getting the expected results that I need. Whenever I try to pass the $_POST variables to the php webservice, my mysqli_query inside always returns nothing with regards to my post variables.
I troubleshooted in both Swift and MySQL and these are the results I'm getting.
In Swift, using print:
["error": Invalid username and/or password., "password": <null>, "username": <null>, "allData": {
"{\n__\"username\"_:_\"Test_User\",\n__\"password\"_:_\"testuser\"\n}" = "";
}]
As seen here, both password and username has null, but when I try to include all the post parameters on the json object I'm returning from the php webservice, it can be seen that I am passing it with the format that I'm not sure of (e.g. "allData": { "{\n__\"username\":\"Test_User\"), ...
This is currently my code on the view controller:
@IBAction func signinTapped(_ sender: Any) {
// Read values from login text fields
let loginUsrVar = loginUsr.text
let loginPwdVar = loginPwd.text
let urlPath = URL(string: "https://website.com/WebServices/CheckUser.php")
var request = URLRequest(url: urlPath!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "content/type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postString = ["username": loginUsrVar!, "password": loginPwdVar!] as [String:String]
let postString:NSDictionary = ["username": loginUsrVar!, "password": loginPwdVar!]
print("postString:", postString)
do {
request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
print("JSON Serialization successful.")
print(request)
} catch let error {
print(error.localizedDescription)
displayMessage(userMessage: "Something went wrong during the login process...")
return
}
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil {
self.displayMessage(userMessage: "Could not successfully perform the request. Please try again later.")
return
}
print("data sent:", data)
print("successful response:", response)
let dataTransformed = NSString(data: request.httpBody!, encoding:String.Encoding.utf8.rawValue)!
print("response encoded:", dataTransformed)
do {
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: [.mutableContainers]) as? NSDictionary
if let jsonResult = jsonResult as? [String: Any] {
print(jsonResult)
}
} catch {
self.displayMessage(userMessage: "Could not successfully perform this request. Please try again later.")
}
}
task.resume()
}
And I'm using a webservice to pull the data that I need for the app with this php code:
<?php
// header("Content-Type: application/json");
// Create connection
$con=mysqli_connect("database_address","username","password","current_app");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM users WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'";
// $sql = "SELECT * FROM users WHERE username='Test User 1' and password = 'testuser'";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
$count = mysqli_num_rows($result);
if ($count == 0 ) { // If no users are found with sql query
// echo "Invalid username and/or password.";
$msg -> error = "Invalid username and/or password.";
$msg -> username = $_POST["username"];
$msg -> password = $_POST["password"];
$msg -> allData = $_POST;
echo json_encode($msg, JSON_UNESCAPED_SLASHES);
// echo $_POST["username"];
} else {
$msg -> greeting = "hello";
$msg -> otherData = $_POST;
echo json_encode($msg);
}
}
// Close connections
mysqli_close($con);
?>
My question is, how do I correctly pull the post variables for the webservice to use?