简体   繁体   English

Android通过PHP和MySQL注册表格

[英]Android Register Form with PHP and MySQL

I'm going to create a simple register form app that when user insert their username and password , EditText in UI shows the id of their record in database. 我将创建一个简单的注册表单应用程序,当用户插入用户名密码时 ,UI中的EditText会在数据库中显示其记录的ID

My app insert users into database correctly; 我的应用程序将用户正确地插入数据库; Just my EditText doesn't show id ... 只是我的EditText不显示id ...

activity_main.xml activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00aeef"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="50dp"
    android:layout_marginTop="18dp"
    android:text="Register Example"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textColor="#ffffff" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/textView3"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="45dp"
    android:text="Username:"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textColor="#ffffff" />

<EditText
    android:id="@+id/edt_username"
    android:layout_width="250dp"
    android:layout_height="40dp"
    android:layout_below="@+id/textView3"
    android:layout_centerHorizontal="true"
    android:background="#ffffff"
    android:ems="10"
    android:padding="5dp" >

    <requestFocus />
</EditText>

<Button
    android:id="@+id/btn_insert"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/edt_result"
    android:layout_below="@+id/edt_password"
    android:layout_marginTop="16dp"
    android:background="#ffffff"
    android:text="Insert"
    android:textColor="#00aeef" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView1"
    android:layout_below="@+id/edt_username"
    android:text="Password:"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textColor="#ffffff" />

<EditText
    android:id="@+id/edt_password"
    android:layout_width="250dp"
    android:layout_height="40dp"
    android:layout_alignLeft="@+id/edt_username"
    android:layout_below="@+id/textView2"
    android:background="#ffffff"
    android:ems="10"
    android:padding="5dp" />

<EditText
    android:id="@+id/edt_result"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_below="@+id/btn_insert"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="22dp"
    android:background="#ffffff"
    android:ems="10"
    android:padding="5dp" />

</RelativeLayout>

InsertClass.java InsertClass.java

package com.example.testphp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class InsertClass extends AsyncTask<String, Void, String>{

private Context context;
private ProgressDialog pDialog;
private EditText edt;
private String json = "";   
private JSONObject jObj = null;

public InsertClass(Context context, EditText edt)
{
    this.context = context;
    pDialog = new ProgressDialog(context);
    this.edt = edt;
}

@Override
protected void onPreExecute() {
    pDialog.setMessage("Loading... Please wait");
    pDialog.show();
    super.onPreExecute();
}

@Override
protected String doInBackground(String... arg0) {

    try
    {
    String username = (String)arg0[0];
    String password = (String)arg0[1];
    String link = "http://10.0.2.2:8020/test/test.php";
    String data = URLEncoder.encode("username","utf-8") + 
    "=" + URLEncoder.encode(username,"utf-8");
    data += "&" + URLEncoder.encode("password","utf-8") + 
            "=" + URLEncoder.encode(password,"utf-8");
    URL url = new URL(link);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
    BufferedReader reader = new BufferedReader
            (new InputStreamReader(conn.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while((line = reader.readLine()) != null)
    {
        sb.append(line);
        break;
    }
    json = sb.toString();
    jObj = new JSONObject(json);
    edt.setText(jObj.getString("id"));
    return sb.toString();
    }
    catch(JSONExeption e)
    {
        return new String("Exeption: " + e.getMessage());
    }
    catch(Exception e)
    {
        return new String("Exeption: " + e.getMessage());
    }
}

@Override
protected void onPostExecute(String result) {
    pDialog.dismiss();
    super.onPostExecute(result);
}
}

MainActivity.java MainActivity.java

package com.example.testphp;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

String username;
String password;
EditText edtUsername;
EditText edtPassword;
EditText edtResult;
Button btnInsert;


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

    btnInsert = (Button) findViewById(R.id.btn_insert);
    edtPassword = (EditText) findViewById(R.id.edt_password);
    edtUsername = (EditText) findViewById(R.id.edt_username);
    edtResult = (EditText) findViewById(R.id.edt_result);

    btnInsert.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            username = edtUsername.getText().toString();
            password = edtPassword.getText().toString();
            new InsertClass(MainActivity.this, edtResult).execute(username,password);

        }
    });

}

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

test.PHP test.php的

<?php

$con = mysqli_connect("localhost" , "root" , "","test");
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_errno();
} 
$username = $_POST['username'];
$password = $_POST['password'];

$result = mysqli_query($con,"INSERT INTO test (username,pass) VALUES '$username','$password')");
if($result)
{
$id_result = mysqli_query($con,"SELECT id FROM test WHERE username = $username");
if($id_result)
{
$response = array("id" => $id_result);
echo json_encode($response);
}
}
mysqli_close($con);
?>

Any suggestion, would be appreciated ... 任何建议,将不胜感激...

Far as I can see, you have 2 errors in your SQL. 据我所知,您的SQL中有2个错误。

This line is missing a bracket: 该行缺少括号:

$result = mysqli_query($con,"INSERT INTO test (username,pass) VALUES  '$username','$password')");
                                                                     ^ bracket

Which should read as: 内容应为:

$result = mysqli_query($con,"INSERT INTO test (username,pass) VALUES ('$username','$password')");

This line is missing quotes for $username 该行缺少$username引号

$id_result = mysqli_query($con,"SELECT id FROM test WHERE username = $username");

Which should read as: 内容应为:

$id_result = mysqli_query($con,"SELECT id FROM test WHERE username = '$username'");

Add or die(mysqli_error($con)) to mysqli_query() to see the actual error. mysqli_query()添加or die(mysqli_error($con)) mysqli_query()以查看实际错误。

You should also guard against SQL injection, change your POST variables to: 您还应该防止SQL注入,将POST变量更改为:

$username = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($con, $_POST['username']);

$password = stripslashes($_POST['password']);
$password = mysqli_real_escape_string($con, $_POST['password']);

Look into mysqli with prepared statements , or PDO with prepared statements , they're much safer . 用预处理语句研究mysqli用预处理语句研究PDO它们更加安全

I won't be able to help you with the Android code, but see what Selvin mentioned in a comment: 我将无法为您提供Android代码,但请参阅Selvin在评论中提到的内容:

"you are catching an exception and do nothing with it (do at least e.printStackTrace() to see it in Logcat) ... and i'm pretty sure that you are hurting UI with bad touch, UI doesn't like to be touched from not UI thread" “您正在捕获异常,对此不采取任何措施(至少要执行e.printStackTrace()才能在Logcat中看到它)……而且我很确定您触摸不良会伤害到UI,UI不愿意从非UI线程被感动”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM