有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从Android应用程序将数据插入MySQL数据库。数据库中未反映的更改

我正在编写一个将数据插入MySQL数据库的应用程序。我用PHP编写了sql查询,当我在安卓应用程序中输入值时,我在log cat中没有看到任何错误,但是这些值没有存储在数据库中

以下是PHP代码:

<?php

$connect = mysqli_connect("localhost","root","","easyassigndroid");

if(mysqli_connect_errno($connect))
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
    echo "success";
}

$username = isset($_POST['sPhone']) ? $_POST['sPhone'] : '';
$password = isset($_POST['sPassword']) ? $_POST['sPassword'] : '';

$query = mysqli_query($connect, "insert into users (sphone, spassword) values ('$username' ,'$password') ");

mysqli_close($connect);
?>

以下是安卓部分:

protected void onCreate(Bundle savedInstanceState) {

    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.register_lecturer);

    phonenum = (EditText) findViewById(R.id.id_phone);
    password = (EditText) findViewById(R.id.id_password);

    sPhone = phonenum.toString();
    sPassword = password.toString();

    registerLecturer=(Button)findViewById(R.id.lecturerregister);
    registerLecturer.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            httpclient = new DefaultHttpClient();
            httppost = new HttpPost("http://10.0.2.2/project/insert.php");

            try
            {
                nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("sphone", sPhone));
                nameValuePairs.add(new BasicNameValuePair("spassword", sPassword));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                response = httpclient.execute(httppost);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    });


}

我是Android和PHP编码的初学者。有人能告诉我代码中的问题在哪里吗?我的项目工作需要这个


共 (2) 个答案

  1. # 1 楼答案

    只有一点:从我们使用的Android EditText中获取值

    x.getText().toString(); 
    

    其中x是EditText对象,对吗?希望能有所帮助

    但是,由于这是在onCreate()中完成的,而不是在onClick()中完成的,因此您应该更改:

    nameValuePairs.add(new BasicNameValuePair("sphone", sPhone));
    

    nameValuePairs.add(new BasicNameValuePair("sphone", phonenum.getText().toString()));
    

    另一个也一样。 干杯

  2. # 2 楼答案

    正如我所看到的,你正在使用“sPhone”和“sPhone”作为键。我建议两者的名字相同

    nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("sphone", sPhone));
    nameValuePairs.add(new BasicNameValuePair("spassword", sPassword));
    

    在PHP中

    $_POST['sphone']
    $_POST['spassword']