IOS应用程序将无法连接到MySQL数据库

IOS应用程序将无法连接到MySQL数据库

问题描述:

firstly I just want to say i'm still new to Objective C so if you could explain in detail it would be most appreciated. Okay so I have an application that has a login scree, I'm trying to then make the app connect to my database i've setup. I'm reading the xCode log and it says it's connected to the database successfully, but when I type in the login that I have on the database it says Invalid login.

Here's the code that i've got to connect to the php file

- (IBAction)login:(id)sender {

    NSInteger success = 0;
    @try {

    if([[self.txtEmail text] isEqualToString:@""] || [[self.txtPassword text] isEqualToString:@""] ) {

        [self alertStatus:@"Please enter Email and Password" :@"Sign in Failed!" :0];

    } else {
        NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[self.txtEmail text],[self.txtPassword text]];
        NSLog(@"PostData: %@",post);

        NSURL *url=[NSURL URLWithString:@"http://repayment.tk/login.php"];

        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];

        //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSLog(@"Response code: %ld", (long)[response statusCode]);

        if ([response statusCode] >= 200 && [response statusCode] < 300)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);

            NSError *error = nil;
            NSDictionary *jsonData = [NSJSONSerialization
                                      JSONObjectWithData:urlData
                                      options:NSJSONReadingMutableContainers
                                      error:&error];

            success = [jsonData[@"success"] integerValue];
            NSLog(@"Success: %ld",(long)success);

            if(success == 1)
            {
                NSLog(@"Login SUCCESS");
            } else {

                NSString *error_msg = (NSString *) jsonData[@"error_message"];
                [self alertStatus:error_msg :@"Sign in Failed!" :0];
            }

        } else {
            //if (error) NSLog(@"Error: %@", error);
            [self alertStatus:@"Connection Failed" :@"Sign in Failed!" :0];
        }
    }
}
@catch (NSException * e) {
    NSLog(@"Exception: %@", e);
    [self alertStatus:@"Sign in Failed." :@"Error!" :0];
}
if (success) {
    [self performSegueWithIdentifier:@"login_success" sender:self];
}
}

- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    alertView.tag = tag;
    [alertView show];
}

Here's what i've got in my PHP file located here: http://repayment.tk/login.php

<?php
error_reporting(E_ALL ^ E_DEPRECATED);
ob_start();
$host="MYHOSTNAME"; // Host name 
$username="DB USERNAME"; // Mysql username 
$password="DB PASSWORD"; // Mysql password 
$db_name="DB NAME"; // Database name 
$tbl_name="Users"; // Table name


// Connect to server and select database.

$connect = @mysql_connect($host, $username, $password) or die (@mysql_error());
echo "Connected to MySQL";
$selectdb = @mysql_select_db($db_name, $connect,$tbl_name) or die (@mysql_error());
echo "Connected to Database";
//mysql_select_db($db_name,$tbl_name) or die(mysql_error());


// Define $username and $password 
$username=$_POST['username']; 
$password=md5($_POST['password']);


// To protect MySQL injection (more detail about MySQL injection)
//$username = stripslashes($username);
//$password = stripslashes($password);
//$username = mysql_real_escape_string($username);
//$password = mysql_real_escape_string($password);

$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
echo "returned $result";
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if ($count=="1") {
   echo '{"success":1}';
} else {
echo "Unsuccessful! $count";
}

ob_end_flush();




 ?>

I've removed the sensitive information, but any help would so be appreciated. It seems the app can connect to the database, but maybe querying it is the problem. Any help would be amazing, thank you

EDIT: I've now changed the code to what @ryantxr suggested and i'm getting this output for some reason.

Repayment Calculator[5326:2217531] PostData: username=u&password=p
2016-03-12 10:08:12.530 Repayment Calculator[5326:2217531] -[NSError init] called; this results in an invalid NSError instance. It will raise an exception in a future release. Please call errorWithDomain:code:userInfo: or initWithDomain:code:userInfo:. This message shown only once.
2016-03-12 10:08:12.701 Repayment Calculator[5326:2217531] Response code: 200
2016-03-12 10:08:12.702 Repayment Calculator[5326:2217531] Response ==> {"success":0}
2016-03-12 10:08:12.702 Repayment Calculator[5326:2217531] Success: 0

I ran your PHP code and it is not outputting JSON. The echo statements are a problem. Furthermore, you are using old deprecated PHP functions. I suggest you test your API call first using curl to make sure that it is doing what you expect. After that, you can deal with Objective-c.

Here is a server side code you can use:

<?php

class LoginHandler {

    public $dbHostname = 'DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE';
    public $dbDatabaseName = 'MYSQL-DBNAME-GOES-HERE';
    public $user = 'DATABASE-LOGIN-USERNAME';
    public $password = 'DATABASE-LOGIN-PASSWORD';

    public function handleRequest($arg) {

        $username = $arg['username'] ? $arg['username']: null;
        $password = $arg['password'] ? $arg['password']: null;
        if ( ! $username || ! $password ) {
            $this->fail();
            return;
        }

        try  {
            $dsn = "mysql:dbname={$this->dbHostname};host={$this->dbHostname}";

            $pdo = new PDO($dsn, $this->user, $this->password);
            $sql="SELECT * FROM `user` WHERE `username`='$username' and `password`='$password'";
            $stmt = $pdo->query($sql);
            if ( $stmt->rowCount() > 0 ) {
                $this->success();
                return;
            }
            else {
                $this->fail();
                return;
            }
        }
        catch(PDOException $e) {
            $this->log('Connection failed: ' . $e->getMessage());
            $this->fail();
        }


    }
    function success() {
        echo json_encode(['success' => 1]);
    }
    function fail() {
        echo json_encode(['success' => 0]);
    }

    function log($msg) {
        file_put_contents("login.log", strftime('%Y-%m-%d %T ') . "$msg
", FILE_APPEND);
    }
}

$handler = new LoginHandler();
$handler->handleRequest($_POST);

Here is some test output:

MacBook-Pro:~ me$ curl http://PUT_YOUR_HOSTNAME/ss1.php -d"username=drum&password=pass1"
{"success":0}
MacBook-Pro:~ me$ curl http://PUT_YOUR_HOSTNAME/ss1.php -d"username=drum&password=pass0"
{"success":1}