php - 从 php 和 android 向 mysql 插入值时无法获得正确的响应

标签 php android mysql

我正在开发一个 Android 注册和登录应用程序。登录代码工作正常,但在注册时我总是收到“Exists”作为来自 php 的响应。

如果我删除 sql 插入查询(即/* MySQL 插入查询 */),它就会起作用

我的register.php代码:

    <?php
    $dbhost = "localhost";
    $dbname = "test";
    $dbuser = "root";
    $dbpass = "";

    $conn = mysql_connect($dbhost,$dbuser,$dbpass)
    or
    trigger_error(mysql_error(),E_USER_ERROR);

    mysql_select_db($dbname, $conn);

    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);

    $query_search = "SELECT count(*) FROM aw_poc WHERE email = '$email'";
    $query_exec1 = mysql_fetch_array($query_search);
    $rows = $query_exec1[0];

    /*$query_search = "SELECT * FROM aw_poc WHERE email = '$email'";
    $query_exec1 = mysql_query($query_search) or die(mysql_error());
    $rows = mysql_num_rows($query_exec1);*/

    if ( $rows == 0) {
        $query_insert = "INSERT INTO aw_poc (username, email, password) VALUES ('$username', '$email', '$password')";

        /* MySQL insert query */

        $query_exec2 = mysql_query($query_insert) or die(mysql_error());
        if ($query_exec2) {
            echo "Success";
        }
    } else {
        echo "Exists";
    }

    mysql_close($conn);
?>

无论电子邮件是否存在,上述代码都会插入相同的值 3 次。我已附上数据库表的快照

这是我的 Registration_activity 的 android java 代码:

public class Registration_activity extends Activity{

    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;
    ProgressDialog dialog = null;

    Button ok_btn;
    EditText username,password,re_password,email;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        ok_btn = (Button)findViewById(R.id.signup_btn);
        username = (EditText)findViewById(R.id.rusername_txtbox);
        password = (EditText)findViewById(R.id.rpassword_txtbox);
        re_password = (EditText)findViewById(R.id.re_password_txtbox);
        email = (EditText)findViewById(R.id.email_txtbox);

        ok_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!username.getText().toString().trim().equals("") && !password.getText().toString().trim().equals("") && !re_password.getText().toString().trim().equals("") && !email.getText().toString().trim().equals("")){
                    if(password.getText().toString().trim().equals(re_password.getText().toString().trim())){
                        if(android.util.Patterns.EMAIL_ADDRESS.matcher(email.getText().toString().trim()).matches()){

                            dialog = ProgressDialog.show(Registration_activity.this, "","Creating user...", true);
                             new Thread(new Runnable() {
                                    public void run() {
                                        login();                          
                                    }

                                    private void login() {
                                        try{            

                                            httpclient=new DefaultHttpClient();
                                            httppost= new HttpPost("http://localhost/register.php"); 

                                            nameValuePairs = new ArrayList<NameValuePair>(2);
                                            nameValuePairs.add(new BasicNameValuePair("username",username.getText().toString().trim()));  
                                            nameValuePairs.add(new BasicNameValuePair("password",password.getText().toString().trim())); 
                                            nameValuePairs.add(new BasicNameValuePair("email",email.getText().toString().trim()));  

                                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                                            response=httpclient.execute(httppost);

                                            ResponseHandler<String> responseHandler = new BasicResponseHandler();
                                            final String response = httpclient.execute(httppost, responseHandler);
                                            System.out.println("Response : " + httpclient.execute(httppost, responseHandler)); 
                                            runOnUiThread(new Runnable() {
                                                public void run() {
                                                    dialog.dismiss();
                                                }
                                            });

                                            if(httpclient.execute(httppost, responseHandler).contains("Success")){
                                                runOnUiThread(new Runnable() {
                                                    public void run() {
                                                        Toast.makeText(Registration_activity.this,"Registration Success", Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                                Intent intent = new Intent(Registration_activity.this,Login_activity.class);
                                                startActivity(intent);
                                            }
                                            else if(httpclient.execute(httppost, responseHandler).contains("Exists")){
                                                showAlert("Email-id already used");     
                                            }
                                            else if (httpclient.execute(httppost, responseHandler).contains("Error")){
                                                showAlert("Error!!!");  
                                            }

                                        }catch(Exception e){
                                            dialog.dismiss();
                                            System.out.println("Exception : " + e.getMessage());
                                        }
                                    }

                                    private void showAlert(final String s) {
                                        Registration_activity.this.runOnUiThread(new Runnable() {
                                            public void run() {
                                                AlertDialog.Builder builder = new AlertDialog.Builder(Registration_activity.this);
                                                builder.setTitle("Alert");
                                                builder.setMessage(s)  
                                                       .setCancelable(false)
                                                       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                                           public void onClick(DialogInterface dialog, int id) {
                                                           }
                                                       });                     
                                                AlertDialog alert = builder.create();
                                                alert.show();               
                                            }
                                        });
                                    }
                                  }).start();
                        }
                        else{
                            Toast.makeText(getApplicationContext(), "Email address format error!!!", Toast.LENGTH_LONG).show();
                            email.setText("");
                            email.requestFocus();
                        }
                    }
                    else{
                        Toast.makeText(getApplicationContext(), "Password does not match!!!", Toast.LENGTH_LONG).show();
                        password.setText("");
                        re_password.setText("");
                        password.requestFocus();
                    }
                }
                else{
                    Toast.makeText(getApplicationContext(), "Some details Missing!!!", Toast.LENGTH_LONG).show();
                    username.requestFocus();
                }
            }
        });
    }
}

最佳答案

用这个替换计数逻辑。

$query_search = "SELECT count(*) FROM aw_poc WHERE email = '$email'";
$query_exec1 = mysql_fetch_array($query_search);
$rows = $query_exec1[0];

只是一条建议,不要使用 mysql 命令,其中大多数命令已被弃用。请改用 PDO。

http://php.net/manual/en/book.pdo.php

更新:

您每次都会收到 3 个条目,因为您正在调用 .execute()方法四次:

response=httpclient.execute(httppost);

final String response = httpclient.execute(httppost, responseHandler);

System.out.println("Response : " + httpclient.execute(httppost, responseHandler)); 

if(httpclient.execute(httppost, responseHandler).contains("Success")){}

删除:

response=httpclient.execute(httppost);

替换:

System.out.println("Response : " + httpclient.execute(httppost, responseHandler)); 

if(httpclient.execute(httppost, responseHandler).contains("Success")){}

与:

System.out.println("Response : " + response)); 

if(response.contains("Success")){}

关于php - 从 php 和 android 向 mysql 插入值时无法获得正确的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29295700/

相关文章:

android - 如何检查设备上是否安装了电子邮件客户端

安卓 : Paypal implementation

android - jar 不匹配!修复使用 appcompat_v7 和 Facebook sdk 时的依赖关系。

mysql - 从 innodb 导入到 ndbcluster 时出现问题

php - 瑞典本地银行付款方式

php - 解析sql响应数组

php - 如何从重复行检查 MYSQL 连接中的一个特定结果

Mysql REGEXP 返回结果和匹配值

javascript - 根据选择列表显示更多 div 和表单

php - 如何在 ZF2/ZF3 url view helper 中添加查询参数