我目前正在用Java在Android Studio中开发一个应用程序,而无需赘述太多,我需要该应用程序的一部分才能将活动填充的数据插入MySQL数据库。我正在使用Apache运行php脚本与数据库进行交互。
我知道该应用程序可以正常访问数据库,因为我可以很好地登录该应用程序,并且可以读取表以确保用户ID和密码组合存在。登录功能发送GET请求,我知道这是不安全的,很快就会用POST请求替换它,我只是想先着手应用程序的其他部分。我尝试了POST请求来插入数据,以尝试解决POST请求的问题。
基本上,尽管GET请求读取用户表以获取登录详细信息可以正常工作,但插入新数据却不能。这是我用于插入记录的php:
// Create connection to database
include_once 'db.php';
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// check fields are populated
if (isset($_POST['trip_user_id']) && isset($_POST['trip_place_id'])
&& isset($_POST['start_date']) && isset($_POST['end_date']) && isset($_POST['private_indicator'])) {
$tripUserId = $_POST['trip_user_id'];
$tripPlaceId = $_POST['trip_place_id'];
$tripStartDate = $_POST['trip_start_date'];
$tripEndDate = $_POST['trip_end_date'];
$privateIndicator = $_POST['private_indicator'];
//query to insert record
$sql = "INSERT INTO user_trips (trip_user_id, trip_place_id, trip_start_date, trip_end_date, private_indicator) VALUES
('$tripUserId', '$tripPlaceId', '$tripStartDate', '$tripEndDate', '$privateIndicator');";
// Confirm there are results
if (mysqli_query($con, $sql)) {
// inserted successfully
echo "new record created successfully";
} else {
echo "Error: ;" . $sql . "<br>" . mysqli_error($con);
}
}
// Close connections
mysqli_close($con);
第二行中的db.php由登录php使用并且可以正常工作,如下所示:
// Create connection to database
$con=mysqli_connect("localhost","root","*****","business_trips");
最后,这是发送HTTP请求的Java代码
public JSONArray makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP
try {
// check for request method
if(method == "POST"){
// request method is POST
String paramString = URLEncodedUtils.format(params, "utf-8");
byte[] postData = paramString.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
URL urlObj = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty( "charset", "utf-8");
urlConnection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
urlConnection.setUseCaches( false );
urlConnection.getOutputStream().write(postData);
is = urlConnection.getInputStream();
}else if(method == "GET"){
// request method is GET
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
URL urlObj = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) urlObj.openConnection();
is = urlConnection.getInputStream();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
NameValuePair的“ params”列表是用户输入的信息,当我在调试器中查看时,所有信息都存储在其中。该程序放入代码的'method ==“ POST”'部分。
当程序进入“ while((line = reader.readLine())!= null){”行时,循环永远不会运行,因此reader.readLine立即返回null。当我的php出现语法问题(缺少分号)时,它返回的结果非常好,这使我认为我的php代码在返回成功或错误消息时出现了问题。看起来应该发送回一条SQL错误消息,因为插入的记录也永远不会显示在表中。
我已经穷尽了所有我能想到的选项,已经阅读了多个教程,但似乎都做不到。谁能看到我可能出了问题的地方?
如果我缺少任何详细信息,请告诉我。
谢谢, 迈克