java Android将登录信息发送到MySQL数据库
我有一个活动,用户输入他的/她的姓名、用户名和密码。我想将此信息作为MySQL数据库中的条目发送。这是我的密码:
protected String doInBackground(String... params) {
String reg_url = "http://MyIPAddress:ServerPort#/Register.php";
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
return "Registration Success!";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
代码运行时没有任何错误,但在程序执行后数据库仍然为空。这是我的PHP文件(Register.PHP):
<?php
require "Connection.php"; //Establishes connection to database
$name = $_POST["user"];
$user_name = $_POST["user_name"];
$user_pass = $_POST["user_pass"];
$sql_query = "insert into user_info values('$name','$user_name','$user_pass');";
if (mysqli_real_query($link, $sql_query)) {
echo "<h1> Data Insertion Success! </h1>";
}
else {
echo "Data Insertion Error...";
}
?>
以及连接到数据库的代码(Connection.php):
<?php
$link = mysqli_init();
$success = mysqli_real_connect($link,$host,$user,$password,$db,$port);
if($success) {
echo "<h1> Success! </h1>";
}
else {
echo "Error...".mysqli_connect_error();
}
?>
我是不是遗漏了什么?我非常感谢你的帮助。谢谢
# 1 楼答案
下面是我在doInBackground方法中将数据发送到数据库的代码:
参考:Android login to mysql database
还发现我为服务器输入的端口号不正确。我也解决了这个问题,现在一切似乎都很好。谢谢大家的帮助