gpt4 book ai didi

php - 如何从 IOS 模拟器访问我的服务器 MySql 以快速检索数据

转载 作者:行者123 更新时间:2023-11-28 07:05:55 24 4
gpt4 key购买 nike

这段代码可能有什么问题,我正在尝试进入我的已打开的 MAMP 服务器,我在服务器中有一个 php 文件,我正在其中测试连接等等,这个:

<?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 个 View ,所有 View 都在 swift 中,但重要的是:

//
// 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 文件在/Applications/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";
} }

我在模拟器中safari可以访问到localhost:8888,所以没有连接问题。

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

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

我完成请求的方式可能有什么问题?

EDIT2:我更改了代码并激活了 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"}';
}
}

$stmt 没有在 get_result() 上重新调整任何东西,或者没有进入 while(fetch()) 我只是现在不知道。有帮助吗?

最佳答案

好吧,如果您的 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 脚本正在运行,然后移至该应用程序。

关于php - 如何从 IOS 模拟器访问我的服务器 MySql 以快速检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30643418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com