使用PHP连接数据库与其他方式在Android

问题描述:

好吧,我已经完成了上述任务,但我不满意它。它看起来非常复杂。使用PHP连接数据库与其他方式在Android

我需要一些其他解决方法来解决这个问题,因为我在android开发方面的经验非常少,找不到任何其他方式。

下面是我做过的。我将向您展示访问数据库的简单登录系统。

以下是登录活动。

package com.example.andorid.ersnexus.userlogin; 

import android.app.Activity; 
import android.content.Intent; 
import android.net.ConnectivityManager; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
mport android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

import com.example.andorid.ersnexus.R; 
import 
com.example.andorid.ersnexus.userprofile.homeactivity. 
UserProfileHomeActivity; 
import com.example.andorid.ersnexus.usersignup.UserSignUpActivity; 
import com.example.andorid.ersnexus.util.SharedPreferencesData; 
import com.example.andorid.ersnexus.webservices.BackgroundDbConnector; 


//This is the main activity of the app. 
//It is the user login screen where users logs in or sign up's. 

public class UserLoginActivity extends AppCompatActivity { 

private EditText mUserName; 
private EditText mUserPassword; 
private Button mLoginButton; 
private Button mSignUpButton; 
//private UserBaseHelper mHelper; 
private String userName; 
private String pass; 
//private String password; 
//private String mErno; 
public static Activity mActivity; 
public static Boolean mActive; 

@Override 
public void onCreate (Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_user_login); 

    mActivity = this; 

    Boolean status = SharedPreferencesData.getStoredLoginStatus(UserLoginActivity.this); 
    if(status){ 
     Intent i = new Intent(UserLoginActivity.this, UserProfileHomeActivity.class); 
     startActivity(i); 
    } 

    //mHelper = new UserBaseHelper(this); 


    //user UserName editText in activity_user_login 
    mUserName = (EditText) findViewById(R.id.login_user_name); 


    //PASSWORD editText 
    mUserPassword = (EditText) findViewById(R.id.login_user_pass); 


    //SignUp button 
    mSignUpButton = (Button) findViewById(R.id.sign_up_button); 
    mSignUpButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick (View v) { 
      Intent i = new Intent(UserLoginActivity.this, UserSignUpActivity.class); 
      startActivity(i); 

     } 
    }); 


    //Login Button 
    mLoginButton = (Button) findViewById(R.id.login_button); 
    mLoginButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick (View v) { 
      if(isNetworkAvailableAndConnected()) { 
       /*try { 
        if(!InetAddress.getByName("192.168.2.3").isReachable(5000)){ 
         throw new Exception("Host does not exist::"); 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); 
        Toast.makeText(UserLoginActivity.this, 
          "Server Is Down",Toast.LENGTH_SHORT).show(); 
       }*/ 
       String type = "login"; 
       userName = mUserName.getText().toString(); 
       pass = mUserPassword.getText().toString(); 
       //password = mHelper.fetchUserPass(userName); 
       //mErno = mHelper.fetchErNo(userName); 
       //String fullName = mHelper.fetchFullName(userName); 

       ***BackgroundDbConnector backgroundDbConnector = new 
         BackgroundDbConnector(UserLoginActivity.this); 
       backgroundDbConnector.execute(type, userName, pass);*** 

       SharedPreferencesData.setStoredUsername(UserLoginActivity.this, userName); 
      }else { 
       Toast.makeText(UserLoginActivity.this, 
         "No Internet Connection",Toast.LENGTH_SHORT).show(); 
      } 

     } 
    }); 

} 

@Override 
public void onStart() { 
    super.onStart(); 
    mActive = true; 
} 

@Override 
public void onStop() { 
    super.onStop(); 
    mActive = false; 
} 

private boolean isNetworkAvailableAndConnected() { 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); 

    boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null; 

    return isNetworkAvailable && 
      cm.getActiveNetworkInfo().isConnected(); 
} 

} 

发布请求是通过backgroundTask送来

BackgroundDbConnector backgroundDbConnector = new 
         BackgroundDbConnector(UserLoginActivity.this); 

backgroundDbConnector.execute(type, userName, pass); 

然后在下面的东西在后台的AsyncTask情况:

try { 
       //Fetch the username and password from the background method call. 
       String username = params[1]; 
       String password = params[2]; 

       mHttpURLConnection = URLManager. 
         getConnection(URLManager.LOGIN_URL); 

       //Creating the outputStream 
       OutputStream outputStream = mHttpURLConnection.getOutputStream(); 
       //Writing in the outputStream. 
       BufferedWriter bufferedWriter = new BufferedWriter(new 
         OutputStreamWriter(outputStream, "UTF-8")); 

       //This is for connecting the variables in the app and in the php file. 
       String postData = URLEncoder.encode("username", "UTF-8") + "=" +//$_POST["username"] 
         URLEncoder.encode(username, "UTF-8") + "&" + 
         URLEncoder.encode("password", "UTF-8") + "=" +//$_POST["password"] 
         URLEncoder.encode(password, "UTF-8"); 

       //Feeding the data. 
       bufferedWriter.write(postData); 
       bufferedWriter.flush(); 
       bufferedWriter.close(); 
       outputStream.close(); 

       //Creating an inputStream to fetch the results. 
       InputStream inputStream = mHttpURLConnection.getInputStream(); 

       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
         inputStream, "iso-8859-1")); 

       //Getting the results 
       String result = ""; 
       String line; 
       while ((line = bufferedReader.readLine()) != null) { 
        result += line; 
       } 
       bufferedReader.close(); 
       inputStream.close(); 
       mHttpURLConnection.disconnect(); 
       //Returning the results 
       return result; 
} 

最后的PHP文件如下:

<?php 
require "conn.php"; 

$user_name = $_POST["username"]; 
$user_pass = $_POST["password"]; 

$mysql_qry = "SELECT * FROM student_data WHERE username='$user_name' AND 
password='$user_pass';"; 

$result = mysqli_query($conn, $mysql_qry); 
$row_cnt = mysqli_num_rows($result); 

if($row_cnt > 0){ 
$row = mysqli_fetch_assoc($result); 
$erno = $row["enrollmentnumber"]; 
echo $erno; 
} 
else{ 
echo "Wrong Username or Password"; 
} 
?> 

所以大多数数据库连接做这样的,我需要一些其他方式来做到这一点

我有一个直觉,正如你可以看到任务所需要的背景,在一些处理其他方式,但我没有得到一个...

所以那些谁有Android的良好经验,请指导我通过正确的道路。

在此先感谢那些花时间阅读我的代码的开发人员。

这里是我的项目链接。请看看并测试你是否想要,我会喜欢关于我的代码的意见。

https://github.com/shrungBhatt/ErNexus

+0

你直接把用户输入到数据库中查询 - ***非常糟糕,非常危险*** – FKEinternet

+0

如果我那么我登录,我需要取用户名直接来自editText.Or是你说我应该先加密它,然后发送它,然后解密,然后把它放在查询中? –

+0

他正在谈论你信任用户输入的方式'$ user_name = $ _POST [“username”];'。然后准备好没有安全检查的SQL。 – jagad89

好吧,我发现了一个另类,它很可爱实现。

try { 
      //Fetch the username and password from the background method call. 
      String username = params[1]; 
      String password = params[2]; 

      mHttpURLConnection = URLManager. 
        getConnection(URLManager.LOGIN_URL); 

      //Creating the outputStream 
      OutputStream outputStream = mHttpURLConnection.getOutputStream(); 
      //Writing in the outputStream. 
      BufferedWriter bufferedWriter = new BufferedWriter(new 
        OutputStreamWriter(outputStream, "UTF-8")); 

      //This is for connecting the variables in the app and in the php file. 
      String postData = URLEncoder.encode("username", "UTF-8") + "=" +//$_POST["username"] 
        URLEncoder.encode(username, "UTF-8") + "&" + 
        URLEncoder.encode("password", "UTF-8") + "=" +//$_POST["password"] 
        URLEncoder.encode(password, "UTF-8"); 

      //Feeding the data. 
      bufferedWriter.write(postData); 
      bufferedWriter.flush(); 
      bufferedWriter.close(); 
      outputStream.close(); 

      //Creating an inputStream to fetch the results. 
      InputStream inputStream = mHttpURLConnection.getInputStream(); 

      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
        inputStream, "iso-8859-1")); 

      //Getting the results 
      String result = ""; 
      String line; 
      while ((line = bufferedReader.readLine()) != null) { 
       result += line; 
      } 
      bufferedReader.close(); 
      inputStream.close(); 
      mHttpURLConnection.disconnect(); 
      //Returning the results 
      return result; 
} 

以上全部代码被Volley替换为以下代码。 ,这里是新的代码

StringRequest stringRequest = new StringRequest(Request.Method.POST, URLManager. 
         LOGIN_URL, new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 
         if (response != null && 
           !response.equals("Wrong Username or Password")) { 
          SharedPreferencesData.setStoredLoginStatus(mContext, true); 
          SharedPreferencesData.setStoredErno(mContext, response); 
          mContext.startActivity(new Intent(mContext, 
            UserProfileHomeActivity.class)); 
         } else { 
          Toast.makeText(mContext, "Wrong Username or Password!", 
            Toast.LENGTH_SHORT) 
            .show(); 
         } 
        } 
       }, new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         Toast.makeText(UserLoginActivity.this, error.toString(), 
           Toast.LENGTH_SHORT).show(); 

        } 
       }) { 
        @Override 
        protected Map<String, String> getParams() { 
         Map<String, String> params = new HashMap<>(); 
         params.put(KEY_USERNAME, userName); 
         params.put(KEY_PASSWORD, pass); 
         return params; 
        } 
       }; 

       SharedPreferencesData.setStoredUsername(UserLoginActivity.this, userName); 

       RequestQueue requestQueue = Volley.newRequestQueue(UserLoginActivity.this); 
       requestQueue.add(stringRequest);