在iOS到MySQL数据库上创建登录的最佳方法是什么?

时间:2012-03-27 13:10:21

标签: mysql ios ipad login

我有一个可以用PHP登录的网站。现在我正在尝试在iPad上创建相同的登录页面。

我有两个文本字段和一个登录按钮,当我点击登录时,它就像这样设置:

-(IBAction)login:(id)sender {
    NSString *username = usernameTextfield.text; 
    NSString *password = passwordTextfield.text;

    NSString *anURL;

    anURL = @"http://www.mydomain.com/login.php";

    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:anURL]];
    [request setHTTPMethod:@"POST"];

    NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@", username, password];
    [request setHTTPBody:[post dataUsingEncoding:NSASCIIStringEncoding]];

    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

    NSString *dataStr = [NSString stringWithFormat:@"%@", responseData];

    [statusLabel setText:dataStr]; // This is just to see what data I get back…
}

这是我的PHP文件“login.php”:

<?php

include("config.php"); //<- db connection

session_start();

$message = "";

$username = stripslashes(mysql_real_escape_string($_POST['username'])); 
$password = stripslashes(mysql_real_escape_string($_POST['password']));

$submit = $_POST["submit_login"];

$md5_password = md5($password);

    $sql = "SELECT * FROM usr_table WHERE usr_name = '$username' and md5_password = '$md5_password'";
    $result = mysql_query($sql);

    $count = mysql_num_rows($result);

    if($count == 1) {
        $user_fetch = mysql_fetch_array($result);
        $_SESSION['usr_id'] = $user_fetch['usr_id'];
        $_SESSION['usr_name'] = $user_fetch['usr_name'];

        $message = "Login OK";

    } else {
        $message = "Login NOT OK";
    }

echo $message;

?> 

我似乎只是以HEX格式恢复数据?我该如何翻译并以良好的方式对待它?我是在这时登录还是更好的方式呢?

提前致谢, ViktorGidlöf

1 个答案:

答案 0 :(得分:0)

从服务器收到响应后,应将其从NSData转换为NSString:

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *responseStr = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(@"%@", responseStr);

您也可以考虑改为发出异步请求,以免在等待响应时阻止应用中的主线程。