我想通過服務器端PHP腳本連接我的libGDX(java)android項目與mySQL數據庫,以便使用POST方法實現登錄過程包括用戶名和密碼)。Android(libGDX)使用PHP服務器端腳本與mySQL的http連接
因此,我面臨着難以預料的問題。爲了您的信息,我在本地使用XAMPP和APACHE Web服務器。
我正面臨着什麼!有些時候,PHP腳本返回以下響應字符串,彷彿不認識的POST參數(儘管POST消息包括他們和包含的值(字符串的事實)!!):
<b>Notice</b>: Undefined index: username in <b>C:\xampp\htdocs\login\login.php</b> on line <b>5</b><br />
<br />
<b>Notice</b>: Undefined index: password in <b>C:\xampp\htdocs\login\login.php</b> on line <b>6</b><br />
一些其他的調試器(在Android studio上)可以顯示調試日誌,按下2-5次btnclickLogin()(如下所示)後會停止顯示任何日誌,該日誌會實現登錄活動。
這聽起來對我來說,http連接掛斷,也許點擊按鈕的監聽器不再響應!
更奇怪的是,有些時候相同的代碼,返回「成功」,一切工作正常。
Android的代碼是下一個
private void btnclickLogin() {
//Getting values from edit texts
Gdx.app.setLogLevel(Application.LOG_DEBUG);
final String username = usernamefld.getText().toString().trim();
final String password = passwordfld.getText().toString().trim();
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("username", username);
parameters.put("password", password);
Gdx.app.debug("Login process started.", "Username=/" + username + "/ Password=/" + password + "/");
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest;
httpRequest = requestBuilder.newRequest().method(Net.HttpMethods.POST).url("http://192.168.1.2/login/login.php").content(HttpParametersUtils.convertHttpParameters(parameters)).build();
httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setTimeOut(6000);
Gdx.net.sendHttpRequest(httpRequest, new HttpResponseListener() {
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String status = httpResponse.getResultAsString().trim();
Gdx.app.debug("Return result by the server=", status);
if(status.contains("success"))
game.setScreen(new StartingScreen(game));
}
@Override
public void failed(Throwable t) {
String status = "failed";
Gdx.app.debug("Connection failed due to the next error:", t.getMessage());
}
@Override
public void cancelled() {
}
});
httpRequest.reset();
Gdx.app.debug("Exiting", "From login button function");
}
PHP腳本
對於login.php中
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//Creating sql query
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
//importing dbConnect.php script
require_once('dbConnect.php');
//executing query
$result = mysqli_query($con,$sql);
//fetching result
$check = mysqli_fetch_array($result);
//if we got some result
if(isset($check)){
//displaying success
echo "success";
}else{
//displaying failure
echo "failure";
}
mysqli_close($con); }?>
對於dbConnect.php
<?php
define('HOST',"localhost");
define('USER',"root");
define('PASS',"");
define('DB',"userlogging");
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Connection failed: ' . $conn->connect_error);
$con->set_charset("utf8"); ?>
請舉個手克服這個問題並使http連接「穩定」!
非常感謝。
你可以通過使用print_r($ _ SERVER)來檢查你在php腳本的$ _SERVER中獲得的所有值嗎? –