I am a beginner in PHP development, I have 'User' Table in my database like below, as we can see the 'id' and 'emailConfirmed' are actually Integer.
to get user data from database, I use this PHP code below, here is the simplified code I use :
class access {
public $host = null;
public $username = null;
public $password = null;
public $dbname = null;
public $conn = null;
public $result = null;
function __construct($xhost,$xusername,$xpassword,$xdbname) {
$this->host = $xhost;
$this->username = $xusername;
$this->password = $xpassword;
$this->dbname = $xdbname;
}
function getUserData ($username) {
$returnArray = [];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $this -> conn -> query($query);
if ($result != null && (mysqli_num_rows($result)>0)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnArray = $row;
}
}
return $returnArray;
}
}
require_once("security/access.php");
$username = htmlentities(strtolower(stripcslashes($_REQUEST["username"])));
$password = htmlentities(strtolower(stripcslashes($_REQUEST["password"])));
if (empty($username) || empty($password)) {
$returnArray = [
"status" => "400",
"message" => "missing required information"
];
echo json_encode($returnArray);
return;
}
$file = parse_ini_file("../../../twitter.ini");
$dbhost = trim($file["host"]);
$dbusername = trim($file["username"]);
$dbpassword = trim($file["password"]);
$dbname = trim($file["dbname"]);
$access = new access($dbhost,$dbusername,$dbpassword,$dbname);
$access->connect();
$user = $access -> getUserData($username);
if (empty($user)) {
$returnArray = [
"status" => "403",
"message" => "User is not found"
];
echo json_encode($returnArray);
return;
} else {
$passwordDB = $user["password"];
if (password_verify($password,$passwordDB)) {
//login successfully
$returnArray = [
"status" => "200",
"message" => "Login Success!",
"id" => $user["id"],
"username" => $user["username"],
"email" => $user["email"],
"avatar" => $user["avatar"],
"fullname" => $user["fullname"],
"emailConfirmed" => $user["emailConfirmed"]
];
} else {
$returnArray = [
"status" => "403",
"message" => "Password didn't match"
];
}
}
$access ->disconnect();
echo json_encode($returnArray);
I use that code for my iOS app, and directly save the user data to local database (data persistence user default) after getting it from the server like below, as we can see the 'id' and 'emailConfirmed' now become string, not Integer anymore.
I don't think I made data type manipulation in the client side code, did I make a mistake in my PHP code so my Integer now become String? or is it in the client side code mistake ? here is my code in swift to make a request and to save the data locally using user default.
// connect to MySQL database
let url = URL(string: "http://localhost/twitter/login.php")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let body = "username=\(usernameTextField.text!)&password=\(passwordTextField.text!)"
request.httpBody = body.data(using: .utf8)
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
if error == nil {
DispatchQueue.main.async {
self.activityIndicator.startAnimating()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
guard let parsedJSON = json else {
print ("error while parsing JSON")
return
}
let status = parsedJSON["status"] as! String
let message = parsedJSON["message"] as! String
if status == "403" {
self.activityIndicator.stopAnimating()
self.showAlert(alertTitle: "ooppss!", alertMessage: message, actionTitle: "OK")
return
} else {
let confirmedUser = parsedJSON["emailConfirmed"] as! String
if confirmedUser == "1" {
UserDefaults.standard.set(parsedJSON, forKey: "parsedJSON")
userInfo = UserDefaults.standard.object(forKey: "parsedJSON") as? NSDictionary
self.activityIndicator.stopAnimating()
self.performSegue(withIdentifier: "goToHomePage", sender: self)
} else {
self.activityIndicator.stopAnimating()
self.showAlert(alertTitle: "sorry", alertMessage: "please complete your registration process first, please check your email", actionTitle: "OK")
}
print(parsedJSON)
}
} catch {
print("\n\n===========Error===========")
print("Error Code: \(error._code)")
print("Error Messsage: \(error.localizedDescription)")
if let data = data, let str = String(data: data, encoding: String.Encoding.utf8){
print("Server Error: " + str)
}
debugPrint(error)
print("===========================\n\n")
}
}
} else {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = error!.localizedDescription
self.showAlert(alertTitle: "oppps", alertMessage: message, actionTitle: "OK")
})
}
})
task.resume()
}
}
so what went wrong in here?