我正在尝试处理个人项目,而我正在实施登录系统。目前,我希望应用程序连接到数据库并查询该数据库中的信息,即用户名和密码。在那一刻我确实认为我的应用程序成功连接到数据库,但由于某种原因查询表不起作用。
这是我在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/app_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];
}
以下是Xcode连接到的PHP文件的内容:
<?php
class LoginHandler {
public $dbHostname = 'mysql.hostinger.co.uk';
public $dbDatabaseName = 'DATABASE NAME';
public $user = 'ADMIN USER';
public $password = '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);
应用程序运行,加载并且似乎允许数据输入绝对精细。只需输入用户名和&amp;密码我总是收到错误消息“登录失败!”即使我已确保该表包含相应的用户名和密码。任何帮助将不胜感激,我似乎在这一刻打了一个砖墙。
此外,我不知道这是否与我的xcode输出框相关,我可以看到以下消息,我想知道这是否是原因:
2016-03-14 11:43:10.956 Repayment Calculator[6539:2753208] PostData: username=a&password=a
2016-03-14 11:43:10.956 Repayment Calculator[6539:2753208] -[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-14 11:43:11.237 Repayment Calculator[6539:2753208] Response code: 200
2016-03-14 11:43:11.238 Repayment Calculator[6539:2753208] Response ==> {"success":0}
2016-03-14 11:43:11.238 Repayment Calculator[6539:2753208] Success: 0
这里还有SQL中表'user'的内容:
-- phpMyAdmin SQL Dump
-- version 3.5.2.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 14, 2016 at 12:04 PM
-- Server version: 10.0.20-MariaDB
-- PHP Version: 5.2.17
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `u948870604_data`
--
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`username` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`username`, `password`, `email`) VALUES
('a', 'a', 'a');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;