2015-06-04 54 views
1

这段代码有什么问题,我试图进入我的MAMP服务器打开,我有一个PHP文件在服务器,米测试连接,这样的做法是:如何从IOS模拟器访问我的服务器MySql检索数据swift

<?php 
header('Content-type: application/json'); 
if($_POST) { 
    $username = $_POST['username']; 
    $password = $_POST['password']; 
    echo $username 
    echo $password 

    if($username && $password) { 

      $db_name  = 'DBTest'; 
      $db_user  = 'pedro'; 
      $db_password = 'pedro'; 
      $server_url = 'localhost'; 

      $mysqli = new mysqli('localhost', $db_user, $db_password, $db_name); 

      /* check connection */ 
      if (mysqli_connect_errno()) { 
       error_log("Connect failed: " . mysqli_connect_error()); 
       echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}'; 
      } else { 
       if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username = ? and password = ?")) { 

        $password = md5($password); 

        /* bind parameters for markers */ 
        $stmt->bind_param("ss", $username, $password); 

        /* execute query */ 
        $stmt->execute(); 

        /* bind result variables */ 
        $stmt->bind_result($id); 

        /* fetch value */ 
        $stmt->fetch(); 

        /* close statement */ 
        $stmt->close(); 
       } 

       /* close connection */ 
       $mysqli->close(); 

       if ($id) { 
        error_log("User $username: password match."); 
        echo '{"success":1}'; 
       } else { 
        error_log("User $username: password doesn't match."); 
        echo '{"success":0,"error_message":"Invalid Username/Password"}'; 
       } 
      } 
    } else { 
     echo '{"success":0,"error_message":"Invalid Username/Password."}'; 
    } 
}else { 
    echo '{"success":0,"error_message":"Invalid Data."}'; 
} 
?> 

而且在Xcode的应用目前有3次都在迅速的,但重要的是这样的:

// 
// LogInViewController.swift 
// ParkingApp 
// 
// Created by Pedro Alonso on 02/06/15. 
// Copyright (c) 2015 Pedro Alonso. All rights reserved. 
// 

import UIKit 

class LogInViewController: UIViewController { 

    @IBOutlet weak var loginLabel: UILabel! 
    @IBOutlet weak var usernameField: UITextField! 
    @IBOutlet weak var passwordField: UITextField! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


    /* 
    // MARK: - Navigation 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     // Get the new view controller using segue.destinationViewController. 
     // Pass the selected object to the new view controller. 
    } 
    */ 

    @IBAction func enterTapped(sender: UIButton) { 

     var username: String = usernameField.text 
     var password: String = passwordField.text 


     if (username.isEmpty || password.isEmpty) { 

      var alertView: UIAlertView = UIAlertView() 
      alertView.title = "Failed" 
      alertView.message = "Error in the username or password" 
      alertView.delegate = self 
      alertView.addButtonWithTitle("Ok") 
      alertView.show() 


     } else { 

      var post: String = "username=\(username)&password=\(password)" 

      NSLog("Post data: %@", post) 
      println(post) 

      var url: NSURL = NSURL(string: "http://localhost:8888/jsonlogin2.php")! 

      var postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)! 

      var postLenght: String = String(postData.length) 

      var request: NSMutableURLRequest = NSMutableURLRequest(URL: url) 

      request.HTTPMethod = "POST" 

      request.HTTPBody = postData 

      request.setValue(postLenght, forHTTPHeaderField: "Content-Length") 

      request.setValue("application/x-form-urlencoded", forHTTPHeaderField: "Content-Type") 

      request.setValue("application/json", forHTTPHeaderField: "Accept") 

      var responseError: NSError? 

      var response: NSURLResponse? 

      var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError) 

      if urlData != nil { 

       let res = response as! NSHTTPURLResponse! 

       println(urlData) 

       NSLog("Response code: %ld", res.statusCode) 

       if (res.statusCode >= 200 && res.statusCode < 300) { 

        var responseData: NSString = NSString(data: urlData!, encoding: NSUTF8StringEncoding)! 

        NSLog("Response: ==> %@", responseData) 

        var error: NSError? 

        let jsonData: NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary 

        let succes: Int = jsonData.valueForKey("succes") as! Int 

        if succes == 1 { 

         NSLog("Login Success") 

         var prefs: NSUserDefaults = NSUserDefaults.standardUserDefaults() 

         prefs.setObject(username, forKey: "USERNAME") 

         prefs.setInteger(1, forKey: "ISLOGGEDIN") 

         prefs.synchronize() 

         self.dismissViewControllerAnimated(true, completion: nil) 


        } else { 

         var errorMsg: String? 

         if jsonData["error_message"] as? String != nil { 

          errorMsg = jsonData["error_message"] as! String? 

         } else { 

          errorMsg = "Unknown error" 
         } 

         var alertView: UIAlertView = UIAlertView() 

         alertView.title = "Sign in failed" 

         alertView.message = errorMsg 
         alertView.delegate = self 
         alertView.addButtonWithTitle("Ok") 
         alertView.show() 


        } 


       } else { 

        var alertView:UIAlertView = UIAlertView() 
        alertView.title = "Sign in Failed!" 
        alertView.message = "Connection Failed" 
        alertView.delegate = self 
        alertView.addButtonWithTitle("OK") 
        alertView.show() 
       } 


      } else { 

       var alertView:UIAlertView = UIAlertView() 
       alertView.title = "Sign in Failed!" 
       alertView.message = "Connection Failure" 
       if let error = responseError { 
        alertView.message = (error.localizedDescription) 
       } 
       alertView.delegate = self 
       alertView.addButtonWithTitle("OK") 
       alertView.show() 
      } 

     } 

    } 
} 

的PHP文件是/应用程序/ MAMP/htdocs,但不清楚的是为什么给我的响应代码为500,并且我不知道为什么会发生。任何帮助?谢谢。

编辑:响应:

<NSHTTPURLResponse: 0x7fc42149ac60> { URL: http://localhost:8888/jsonlogin2.php } { status code: 500, headers { 
    Connection = close; 
    "Content-Length" = 0; 
    "Content-Type" = "text/html; charset=UTF-8"; 
    Date = "Thu, 04 Jun 2015 12:11:35 GMT"; 
    Server = "Apache/2.2.29 (Unix) mod_wsgi/3.4 Python/2.7.8 PHP/5.6.7 mod_ssl/2.2.29 OpenSSL/0.9.8zd DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.8 Perl/v5.20.0"; 
    "X-Powered-By" = "PHP/5.6.7"; 
} } 

我可以从狩猎访问在模拟器为localhost:8888,所以不存在连接问题。

EDIT2:所以它是要求明显,因为它告诉我无效的数据跳过所有并返回此:

2015-06-04 17:16:11.914 ParkingApp[3777:126598] Response: ==> {"success":0,"error_message":"Invalid Data."} 

什么可能是错误的,我所做的请求的方式?编辑2:我已经改变了代码,并激活了mysql日志查看查询,但仍然$ stmt-> get_result()或fetch()没有做什么,我不知道为什么。我没有在整个IOS中做这件事,但这里的简单浏览器是麻烦的部分。

修改部分:

$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name); 

      /* check connection */ 
      if (mysqli_connect_errno()) { 
       error_log("Connect failed: " . mysqli_connect_error()); 
       echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}'; 
      } else { 
       $query = "SELECT dataOne,password FROM users WHERE username = ? and password = ?"; 

       if ($stmt = $mysqli->prepare($query)) { 

        //$password = md5($password); 

        /* bind parameters for markers */ 
        $stmt->bind_param("ss", $username, $password); 

        /* execute query */ 
        $stmt->execute(); 

        //$stmt->debugDumpParams(); 
        echo $stmt->sqlstate; 
        var_dump($stmt); 

        /* bind result variables */ 
        //$stmt->bind_result($dataOne,$password); 

        $result = $stmt->get_result(); 

        printf("test: ", $dataOne, $password); 

        //fetch value 

        while($stmt->fetch()) { 

         echo $dataOne; 

        } 


        /* close statement */ 
        $stmt->close(); 
       } 

       /* close connection */ 
       $mysqli->close(); 

       if ($result != null) { 
        error_log("User $username: password match."); 
        echo '{"success":1, "dataOne:"'.$dataOne.'}'; 
       } else { 
        error_log("User $username: password doesn't match."); 
        echo '{"success":0,"error_message":"Invalid Username/Password"}'; 
       } 
      } 

的$语句不重新调整对get_result任何东西()或不进入的同时(取()),我只是不知道现在。任何帮助?

回答

1

那么,如果你的web服务器抛出http错误代码500(内部错误),这是因为你的PHP脚本崩溃。我会尝试阅读php日志,并尝试对php脚本进行一些调试。

也许你的iOS应用发布的数据有问题,导致php脚本失败?

在这种情况下,从safari访问localhost:8888也不能证明php脚本正在工作,因为它要求您发布脚本执行的任何数据。 if($_POST) {。通过浏览该脚本,if语句将永远不会是true

编辑:

它有时有助于一次验证一个组件。尝试构建一个简单的html表单,将usernamepassword针对您的服务器发布(http://localhost:8888/jsonlogin2.php)。当你看到这个预期的工作,继续前进,以确保应用程序的作品。这样你就可以知道你的错误是在服务器上(php脚本)还是在你的应用中。

这也是很好的检查$_POST这样的:

if (!empty($_POST)) {} 

这将检查$_POST是空的。

您的应用也在使用application/x-form-urlencoded,我的猜测是这应该是:application/x-www-form-urlencoded

但是再一次。制作一个本地html表单,并确保你的php脚本正在工作,然后转到应用程序。

+0

很明显,错误来自回声$我在我的PHP非常生锈,我会进入它:) –

+0

而无论如何不执行if($ _ POST){}只是抛出无效的数据错误 –

+0

更新答案... –

相关问题