目标 C - 无法查询数据库 (MySQL)


Objective C - Can't query database (MySQL)

我正在尝试处理个人项目,并且正在实现登录系统。目前,我希望应用程序连接到数据库并查询该数据库中的信息,即用户名和密码。目前,我相信我的应用程序已成功连接到数据库,但由于某种原因查询表不起作用。

这是我在 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);

该应用程序运行,加载并且似乎允许输入数据。只是在输入用户名和密码后,我总是收到错误消息"登录失败!"即使我已经确保表格包含相应的用户名和密码。任何帮助将不胜感激,我此刻似乎已经撞到了砖墙。

我也不知道这是否相关,看看我的 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 */;
我相信

这可能是您问题的解决方案 - XCode 与 https 的最新变化:

NSURL 错误代码 1022