[英]Can't insert data into mysql database with android
EditText tv_username;
EditText tv_firstname;
EditText tv_age;
Button reg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_username = (EditText) findViewById(R.id.username);
tv_firstname = (EditText) findViewById(R.id.firstname);
tv_age = (EditText) findViewById(R.id.age);
reg = (Button) findViewById(R.id.register);
reg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/regandroid.php");
if(httppost != null)
{
Context context = getApplicationContext();
CharSequence text = "Connected";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", tv_username.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("firstname", tv_firstname.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("age", tv_age.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
catch(Exception e)
{
e.printStackTrace();
}
這是我的phpcode
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$age = $_POST['age'];
$query = mysql_query($connect, "insert into users
(username, firstname,age) values ('$username'
,'$firstname','$age') ");
?>
也許我的php代碼有問題,我找不到問題所在。這是我的php和java代碼,盡管它已連接到數據庫,但我無法插入數據。 我無法弄清楚我犯了什么錯誤。
mysql_query的參數順序錯誤。
mysql_query(字符串$ query [,資源$ link_identifier = NULL])
鏈接標識符/連接應通過第二個參數添加,而查詢應通過第一個參數添加。
更改:
$query = mysql_query($connect, "insert into users(username, firstname,age) values ('$username', '$firstname', '$age')");
至
$query = mysql_query("insert into users(username, firstname,age) values ('$username', '$firstname', '$age')", $connect);
另外,在將外部數據直接插入查詢中時,您的代碼也可以進行SQL注入。 如果不可以,請使用帶有PDO的預處理語句,或者至少使用mysql_real_escape_string 。
數據庫鏈接並不是真正需要的。 但是,如果通過,則僅在mysql_query語句的末尾傳遞。 即:
$query = mysql_query("insert into users (username, firstname, age) values ('$username', '$firstname', '$age')", $connect);
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.