从Android中的在线数据库获取数据

时间:2016-04-27 14:14:16

标签: php android database

我正在开发一个应用程序,但我在尝试从在线数据库中检索数据时遇到了问题。

所以,在我的MainActivity中我有这个:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button b1;
    EditText ed1,ed2;

    public static final String USER_NAME = "USER_NAME";

    public static final String PASSWORD = "PASSWORD";

    private static final String LOGIN_URL = "http://example.com/login.php";

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

        b1 = (Button) findViewById(R.id.button);
        b1.setOnClickListener(this);

        ed1 = (EditText) findViewById(R.id.editText);
        ed2 = (EditText) findViewById(R.id.editText2);

    }

    private void login(){

        String username = ed1.getText().toString().trim();
        String password = ed2.getText().toString().trim();
        userLogin(username,password);

    }

    private void userLogin( final String username, final String password){

        class UserLoginClass extends AsyncTask<String,Void,String>{
            ProgressDialog loading;
            @Override
            protected void onPreExecute(){
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this,"Please Wait",null,true,true);
            }

            @Override
            protected void onPostExecute(String s){
                super.onPostExecute(s);
                loading.dismiss();
                if(s.equalsIgnoreCase("success")){
                    Intent intent = new Intent(MainActivity.this,MainScreen.class);
                    intent.putExtra(USER_NAME,username);
                    startActivity(intent);
                } else{
                    Toast.makeText(getApplicationContext(), "Wrong Credentials",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            protected String doInBackground(String... params){
                HashMap<String,String> data = new HashMap<>();
                data.put("username",params[0]);
                data.put("password",params[1]);

                RegisterUserClass ruc = new RegisterUserClass();

                String result = ruc.sendPostRequest(LOGIN_URL,data);

                System.out.println(result);
                return result;
            }
        }

        UserLoginClass ulc = new UserLoginClass();
        ulc.execute(username,password);

    }


    @Override
    public void onClick(View v){
        if(v == b1){
            login();
        }
    }
}

在我的RegisterUser课程中,我有这个:

public class RegisterUserClass {

    public String sendPostRequest(String requestURL,
                                  HashMap<String, String> postDataParams) {

        URL url;
        String response = "";
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                response = br.readLine();
            }
            else {
                response="Error Registering";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}

在login.php文件中我有这个:

<?php
define('HOST','host_name');
define('USER','user_name');
define('PASS','password');
define('DB','database');

$con = mysqli_connect(HOST,USER,PASS,DB);

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "select name from register_users where phone='$username' and password='$password'";

$res = mysqli_query($con,$sql);

$check = mysqli_fetch_array($res);

if(isset($check)){
echo 'success';
}else{
echo 'failure';
}

mysqli_close($con);
?>

我能够很好地查找输入的用户名和密码。由于php文件中的select已经有我想从数据库中检索的字段(名称)。我可以在代码中的哪个位置获取在“select”中检索到的信息?

1 个答案:

答案 0 :(得分:0)

您发布的脚本非常容易受到SQL注入或类似攻击,因此您应该考虑使用框架(如Laravel或类似的东西)。

如果要将数据返回到智能手机,最好的方法是将所有结果数据放入数组/对象并以JSON(json_encode

返回