FreeTheStudents
FreeTheStudents

Reputation: 171

Why is my Swift app not connecting to my Database?

Here is the code that I am executing when the user presses the "Register" button on a register page. I just want the script to send the info to my Register.php page then put the email and password into the database.

@IBAction func RegisterButtonTapped(sender: AnyObject) {

    let userEmail = EmailTextField.text
    let userPassword = PasswordTextField.text
    let userRepeatPassword = RepeatPasswordTextField.text

    // Check for empty fields
    if(userEmail.isEmpty || userPassword.isEmpty || userRepeatPassword.isEmpty) {

        // Display alert message

        displayAlertMessage("All fields are required.")

        return;
    }

    // Check if passwords match
    if(userPassword != userRepeatPassword) {
        // Display an alert message
        userPassword == ""
        displayAlertMessage("Passwords do not match.")
        return;
    }

    // Send user data to server side
    let myUrl = NSURL(string: "www.testsite.com/Register.php")
    let request = NSMutableURLRequest(URL: myUrl!)

    request.HTTPMethod = "POST";

    let postString = "email=\(userEmail)&password=\(userPassword)"

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            println("error\(error)")
            return
        }

        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error:&err) as? NSDictionary

        if let parseJSON = json {
            var resultValue = parseJSON["status"] as? String
            println("result: \(resultValue)")

            var isUserRegistered:Bool = false
            if (resultValue=="Success") {
                isUserRegistered = true
            }

            var messageToDisplay = parseJSON["message"] as! String!
            if (!isUserRegistered) {
                messageToDisplay = parseJSON["message"] as! String!
            }

            dispatch_async(dispatch_get_main_queue(), {

                //Display alert message with confirmation
                var myAlert = UIAlertController(title: "Alert", message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)

                let okAction = UIAlertAction(title: "Ok", style:UIAlertActionStyle.Default){ action in
                    self.dismissViewControllerAnimated(true, completion: nil)
                }

                myAlert.addAction(okAction)
                self.presentViewController(myAlert, animated: true, completion: nil)
            });
        }
    }
}

Register.php

<?php
require(“Connect.php”);
require(“SQLData.php”);
$email = htmlentities($_POST[“email”]);
$password = htmlentities($_POST[“password”]);

$returnValue = array();

if(empty($email) || empty($password)) {
    $returnValue[“status”] = “error”;
    $returnValue[“message”] = “Missing required field”;
    echo json_encode($returnValue);
    return;
}

$dao = new SQLData();
$dao->openConnection();
$userDetails = $dao->getUserDetails($email);

if(!empty($userDetails)) {
    $returnValue[“status”] = “error”;
    $returnValue[“message”] = “User already exists”;
    echo json_encode($returnValue);
    return;
}

$secure_password = md5($password); // I do this, so that user password cannot be read even by me

$result = $dao->registerUser($email,$secure_password);

if($result) {
    $returnValue[“status”] = “Success”;
    $returnValue[“message”] = “User is registered”;
    echo json_encode($returnValue);
    return;
}

$dao->closeConnection();

?>'

Upvotes: 0

Views: 1074

Answers (1)

kyngsigma
kyngsigma

Reputation: 1

It is likely that you entered the variable name in mysql incorrectly vs the php db file. They are case sensitive. Check to make sure the the column names in mysql "user" table php script and no spaces. Hope that helps

Upvotes: 0

Related Questions