首先,我只是想说我仍然是Objective C的新手,所以如果你能详细解释一下,我将非常感激。好的,所以我有一个具有登录scree的应用程序,我正在尝试将应用程序连接到我已设置的数据库。我正在阅读xCode日志,它说它已成功连接到数据库,但当我输入我在数据库上的登录时,它显示无效登录。
这是我必须连接到php文件的代码
- (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];
}
以下是我在PHP文件中的内容: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();
?>
我删除了敏感信息,但任何帮助都会受到赞赏。似乎应用程序可以连接到数据库,但可能查询它是问题。任何帮助都会很棒,谢谢
编辑:我现在已经将代码更改为@ryantxr建议的内容,并且由于某种原因我得到了这个输出。
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
答案 0 :(得分:0)
我运行了你的PHP代码而它没有输出JSON。 echo语句是个问题。此外,您正在使用旧的已弃用的PHP函数。我建议您首先使用curl测试您的API调用,以确保它正在执行您期望的操作。之后,您可以处理Objective-c。
以下是您可以使用的服务器端代码:
<?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\n", FILE_APPEND);
}
}
$handler = new LoginHandler();
$handler->handleRequest($_POST);
以下是一些测试输出:
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}