我是 Android 编程新手,我正在尝试接受用户输入并将其添加到我的外部数据库中。现在我的php代码是:
<?php
mysql_connect("host","login","pass") or die ("Unable to connect to MySQL");
mysql_select_db("database");
mysql_query("INSERT INTO Table (number, format, name, price) VALUES ('".$_REQUEST['number1']."', ".$_REQUEST['format1'].", ".$_REQUEST['name1'].", ".$_REQUEST['price1'].")");
mysql_close();
?>
我没有看到我的 php 有任何问题,但是当我运行我的程序时,我没有收到任何错误,但是当我查看我的数据库时,似乎实际上并没有添加任何内容。我的Java代码是:
Log.d("debug", "ENTER METHOD ADD");
new Thread(new Runnable(){
public void run(){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
EditText eNumber = (EditText) findViewById(R.id.barcodeEdit);
EditText eFormat = (EditText) findViewById(R.id.codeFormatEdit);
EditText eName = (EditText) findViewById(R.id.titleEdit);
EditText ePrice = (EditText) findViewById(R.id.priceEdit);
Log.d("debugNumber", eNumber.getText().toString());
Log.d("debugFormat", eFormat.getText().toString());
Log.d("debugName", eName.getText().toString());
Log.d("debugPrice", ePrice.getText().toString());
nameValuePairs.add(new BasicNameValuePair("number1", eNumber.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("format1", eFormat.getText().toString())); //you can add as many you need
nameValuePairs.add(new BasicNameValuePair("name1", eName.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("price1", ePrice.getText().toString()));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://MY_SITE.com/my.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
//is = entity.getContent();
Log.d("debug", "ENDED TRY");
}catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", e.toString());
//return false;
//Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}).start();
那是我添加的代码。我知道我可以很好地连接到数据库,因为我用来搜索数据库的代码可以正常工作,但由于某种原因,我的添加搞砸了。我有代码在一个新线程中运行,因为前几天我了解到您不能在程序的主线程中执行这些 http 请求。我一直在寻找答案,但还没有找到答案,也许我只是漏掉了一行,非常感谢任何帮助。