【发布时间】:2015-02-15 11:53:43
【问题描述】:
我无法将数据插入我的 MySQL 数据库。而且我还向 Android 模块发送了回复,以显示数据是否已保存。
PHP 代码:
$id = $_POST['Id'];
$name = $_POST['Name'];
$email = $_POST['Email'];
$con = new PDO("mysql:host=localhost;dbname=test", "root", "");
$query = "Insert into record values ('$id','$name','$email')";
//$query = "Select * from record";
$result = $con->query($query);
Android 代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new);
final EditText Id = (EditText) findViewById(R.id.editText);
final String id = Id.getText().toString();
final EditText Name = (EditText) findViewById(R.id.editText2);
final String name = Name.getText().toString();
final EditText Email = (EditText) findViewById(R.id.editText3);
final String email = Id.getText().toString();
Button SavePush = (Button) findViewById(R.id.button3);
SavePush.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2:8080/insert.php");
try{
ArrayList NameValuePairs = new ArrayList<NameValuePair>(3);
NameValuePairs.add(new BasicNameValuePair("Id",id));
NameValuePairs.add(new BasicNameValuePair("Name", name));
NameValuePairs.add(new BasicNameValuePair("Email", email));
httpPost.setEntity(new UrlEncodedFormEntity(NameValuePairs));
HttpResponse response = httpclient.execute(httpPost);
}catch (Exception e){e.printStackTrace();}
}
});
}
【问题讨论】:
-
您无法在 UI 线程中与 Internet 通信,您必须使用
Thread或AsyncTask,阅读您的 logcat 以获得有用的数据,您必须获得android.os.NetworkOnMainThreadException以获取有关该阅读的更多信息stackoverflow.com/questions/6343166/… -
问题出在insert into语句中,缺少表名
-
您似乎没有测试 PDO 查询是否成功 - 请参阅手册了解返回值。另外,这里有一个 SQL 注入漏洞,所以如果你不想被黑客入侵,请切换到准备好的语句。
-
您可以使用 XML、JSON 或仅使用 HTTP 响应代码来响应应用程序。那是你可以研究和尝试的东西吗?肯定有例子。
-
@shayanpourvatan 你能告诉我怎么做吗?我需要插入数据并检索