php - Objective C - 无法查询数据库(MySQL)

标签 php mysql objective-c

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

这是我在 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 最近对 http 与 https 的更改:

NSURL Error Code 1022

关于php - Objective C - 无法查询数据库(MySQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35986633/

相关文章:

mysql - 使用 SQL 查找重复项? - 编写 SQL 语句?

objective-c - upSideDown iPhone 方向在 iOS 6 中不起作用?

ios - 将“const char *”发送到“const uint8_t *”类型的参数时出错

php - 在 Laravel Eloquent 查询上隐藏关系

php - 带有 join 的 Sum 函数给出总和乘以 laravel ORM 中条目的次数与 mysql

MySQL 分隔符语法错误

mysql - 解决 "MySQL server has gone away"错误

javascript - 将值从 javascript 函数传递到 php 文件对我不起作用

javascript - 关于发帖请求

ios - 委托(delegate)和方法没有理由不执行