使用Xcode和MySQL为iphone创建基本登录系统 - 连接问题

时间:2014-02-07 17:17:56

标签: php mysql ios iphone xcode

我正在尝试使用Xcode(个人项目)为iPhone应用程序实现基本登录功能,所以此时我不需要考虑安全性。

我开始使用static functionallity,我将数据发布到我本地主机上的URL(使用NAMP),以检查用户名&密码参数与我的php文件中指定的密码参数匹配。

这很好 - 所以我试图编辑php文件,以便它连接到NAMP上托管的MySQL数据库,并在'Customer'表中检查与发布的用户名和密码匹配的用户名和密码。它返回一个计数,如果计数为1,我希望登录成功。

这是我的“登录”按钮中的代码:

- (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://localhost:8888/jsonlogin2.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];
}

这是我的php文件:

<?php
ob_start();
$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password="root"; // Mysql password 
$db_name="coffee"; // Database name 
$tbl_name="Customer"; // Table name


// Connect to server and select database.
mysql_connect("$host", "$username", "$password") or die(mysql_error());
echo "Connected to MySQL";
mysql_select_db("$db_name") or die(mysql_error());
echo "Connected to Database";

// 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();




 ?>

这是我在Xcode调试器中获得的错误代码,无论输入的用户凭据是否与db中的记录匹配。

[38992:a0b] PostData: username=francis&password=pass
[38992:a0b] Response code: 200
TheCoffeeHouse[38992:a0b] Response ==> Connected to MySQLConnected to   Databasereturned Resource id #2Unsuccessful! 0
[38992:a0b] Success: 0

正如你在php文件中看到的那样,我已经使用了:'echo'返回了$ result“;”试着找出发生了什么。不知道它返回的'资源ID#2'是什么。

我还登录了PhpMyAdmin,打开了db并对记录执行了一个简单的SELECT查询,工作正常。所以我推断数据库和应用程序没有正确通信。

最后我应该指出,我对Objective-C很新。

提前感谢您的帮助。

亲切的问候,

Francis

1 个答案:

答案 0 :(得分:0)

这是我的代码,它正在处理我的应用程序。谢谢你的PHP代码。它帮助我看到登录成功。我希望你也能解决问题。

<?php
$username = "root";
$database = "testdb";
mysql_connect("localhost", $username);
@mysql_select_db($database) or die("Unable to find databse");
$name = $_POST["name"];
$password=$_POST['password'];
$query = "SELECT * FROM test WHERE Name = '$name' and Password ='$password' ";
$result = mysql_query($query); 
$rows = array();


while ($r = mysql_fetch_assoc($result))
{
    $rows[] = $r;
}

$count=mysql_num_rows($result);
mysql_close();
if ($count=="1") {
   echo '{"success":1}';
} else {
echo "Unsuccessful! ";
}


?>

- (IBAction)signinTapped:(id)sender {
    NSInteger success = 0;
    @try {
        if ([[self.userTextname text]isEqualToString:@""]||[[self.userTextpassword text] isEqualToString:@""]) {
            [self alertStatus:@"please enter Email and password":@"sign in Failed!":0];
        }else{
            NSString *post = [[NSString alloc ]initWithFormat:@"name=%@&password=%@",[self.userTextname text],[self.userTextpassword text]];
                  NSLog(@"PostData:%@",post);
            NSURL *url = [NSURL URLWithString:@"http://localhost/json.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];

            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{
                  [self alertStatus:@"Connnection Failed" :@"sign in failed!":0];
            }

        }
    }
        @catch (NSException *exception) {
            NSLog(@"Exception: %@",exception);
            [self alertStatus:@"Sign in Failed." :@"Error!":0];

        } if (success) {
            [self performSegueWithIdentifier:@"loginSuccess" sender:self];

        }
    }