我当前正在创建链接到Android Application PHPMyAdmin数据库的MYSQL
Hosting24.com,此活动旨在允许用户注册以在应用程序的EditText框中输入详细信息,该文本将输入到MYSQL数据库中。

我尝试运行的代码给出了Toast输出:

"Sorry, Username already chosen. Please choose another. "即使datbase完全为空。

这似乎是因为JSON response为假,我的查询是为什么这会为假?

这是否意味着PHP脚本中的Access details不正确?

Android代码:

public class SignUp extends Activity {

    EditText UserName, Password;
    Button btnSignUp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up_screen);

        UserName = (EditText) findViewById(R.id.euUserName);
        Password = (EditText) findViewById(R.id.euPass);
        Password.setTransformationMethod(PasswordTransformationMethod.getInstance());
        btnSignUp = (Button) findViewById(R.id.btnSingUp);
        btnSignUp.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                // get The User name and Password to sign up with
                String userName = UserName.getText().toString();
                String password = Password.getText().toString();

                // Url to login PHP script on server
                String serverURL = "http://r999hosting.com/UserRegistrationService.php?username="
                        + userName + "&password=" + password;

                new LongOperation().execute(serverURL);

            }
        });

    }

    /**
     * Contains logic related to communication with PHP script over server
     *
     * @author
     *
     */
    private class LongOperation extends AsyncTask<String, Void, Void> {

        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private ProgressDialog Dialog = new ProgressDialog(SignUp.this);
        String data = "";
        int sizeData = 0;

        protected void onPreExecute() {

            Dialog.setMessage("Please wait.. ");
            Dialog.show();

        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {

            // make POST call to web server
            BufferedReader reader = null;

            try {

                // Define URL where to send data
                URL url = new URL(urls[0]);

                // Send POST data request
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(
                        conn.getOutputStream());
                wr.write(data);
                wr.flush();

                // Get the server response
                reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                // Read Server Response
                while ((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line + "");
                }

                // Append Server Response To Content String
                Content = sb.toString();
            } catch (Exception ex) {
                Error = ex.getMessage();
            } finally {
                try {

                    reader.close();
                }

                catch (Exception ex) {
                }
            }

            return null;
        }

        protected void onPostExecute(Void unused) {

            // Close progress dialog
            Dialog.dismiss();

            if (Error != null) {

            } else {

                // Start Parse Response JSON Data
                String OutputData = "";
                JSONObject jsonResponse;

                try {

                    // Creates a new JSONObject with name/value mappings from
                    // the JSON string
                    jsonResponse = new JSONObject(Content);

                    String result = jsonResponse.get("result").toString();

                    if (result.equals("true")) {
                        // inform user they have signed up successfully
                        Toast.makeText(SignUp.this,
                                "Congrats: Sign Up Successfull",
                                Toast.LENGTH_LONG).show();

                        Intent i = new Intent(SignUp.this,
                                LoginHome.class);
                        startActivity(i);
                        // inform user of error signing up
                        Toast.makeText(getApplicationContext(),
                                "Congrats: Sign Up Successfull",
                                Toast.LENGTH_LONG).show();

                    } else {
                        Toast.makeText(
                                SignUp.this,
                                "Sorry, Username already chosen. Please choose another. ",
                                Toast.LENGTH_LONG).show();
                    }

                }

                catch (JSONException e) {

                    e.printStackTrace();
                }

            }
        }

    }


}


PHP脚本:(注意:出于安全原因,未显示真实详细信息)

<?php



if(isset($_GET['username']) && isset($_GET['password']))
{

$mysql_host = " ";
$mysql_database = " ";
$mysql_user = " ";
$mysql_password = " ";


// Provide host ip, mysql user name, password
 $con = mysql_connect($mysql_host,$mysql_user,$mysql_password);

// Provide database name.
mysql_select_db($mysql_database);



    $username=$_GET['username'];

    $password=$_GET['password'];

    $flag="false";


    if(!empty($username) && !empty($password))
    {

        $sql="Insert into `Login` (`UserName`,`Password`)  values ('$username','$password') ";

        $result=mysql_query($sql);

        if($result)
        {
            $count= mysql_affected_rows();
            if($count > 0)
            {
                $flag="true"; //result true

            }

        }

                   mysql_close($con);
        echo json_encode(array("result"=>$flag));
    }



}

?>

最佳答案

您已将userNamepassword硬编码到URL中,对于GET可以,但对于POST而言,可以;对于POST请求,您需要在请求正文中发送查询参数。

将查询字符串分别传递给您的后台任务,因此可以使用它设置data字段。

    // Url to login PHP script on server
        String serverURL = "http://r999hosting.com/UserRegistrationService.php"

        String query = "username=" + userName + "&password=" + password;
        new LongOperation().execute(serverURL, query);


您可能要properly encode the query see this question

更改您的doInBackground以设置本地data变量。

        protected Void doInBackground(String... urls) {
            data = urls[1]
            ...

08-06 13:50