So I am using swift 2 to develop an app. I have a database on phpmyadmin and am hosting using MAMP (so locally). I'm trying to create a simple registration page for my app, so once a user enters a username and password it should store it into my database. My database is called userAccounts and the table is called users. It has two columns: username and password. I have written code both in my swift file and php file, but it is not inserting into my database. I have not found out why.
This is the swift file:
@IBOutlet var usernameTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pressButton(sender: AnyObject) {
let request = NSMutableURLRequest(URL: NSURL(string: "file:///Applications/MAMP/htdocs/userInsert.php")!)
request.HTTPMethod = "POST"
let postString = "a=\(usernameTextField.text!)&b=\(passwordTextField.text!)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
this is the php file:
$user = 'x';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'@'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
$username = $_POST['a'];
$password = $_POST['b'];
$sql = "INSERT INTO `userAccounts`.`users` (`username`, `password`)
VALUES ('$username','$password')";
$result = mysqli_query($link, $sql);
echo "inserted into database Successfully"
mysqli_close($link);
}
else {
die('comment is not set or not containing valid value');
}
when I run my app, prints out my entire php file in the console and does not actually insert anything into my database. Any idea what I might be doing wrong?
Change your initialisation of NSMutableURLRequest from:
let request = NSMutableURLRequest(URL: NSURL(string: "file:///Applications/MAMP/htdocs/userInsert.php")!)
to:
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost/userInsert.php")!)