Mysql
 sql >> Baza danych >  >> RDS >> Mysql

Jak zweryfikować dane logowania użytkownika w Androidzie za pomocą PHP, MySql za pomocą json

Zrobiłem ten kod dla mojego projektu. i działa dobrze. Spróbuj.

Login2.php

<?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db

$host="localhost"; // Host name 
$user="root"; // Mysql username 
$pswd=""; // Mysql password 
$db="database_name"; // Database name 
$tbl_name="user_info"; // Table name

$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
//$query = "SELECT * FROM $tbl_name WHERE first_name = '$un' AND password = '$pw'";
$query = "SELECT emp_id FROM $tbl_name WHERE first_name = '$un' AND password = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) > 0)
echo mysql_result($result,0);  // for correct login response
else
echo 0; // for incorrect login response
?>

Kod Java dla Androidlogin.java

weź dwa edittext i przycisk i kliknij przycisk wstaw tę metodę code.delete saveperference , której nie chcesz zapisywać nazwy użytkownika , emp_id do całej aplikacji.

    @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                    postParameters.add(new BasicNameValuePair("username", username
                            .getText().toString()));
                    postParameters.add(new BasicNameValuePair("password", password
                            .getText().toString()));
                    // String valid = "1";
                    String response = null;
                    try {
                        // "http://10.0.2.2//Mobile/login2.php"
                        response = CustomHttpClient
                                .executeHttpPost(
                                        "http://10.0.2.2//Mobile/login2.php",
                                        postParameters);
// now in result you will have the response from php file either 0 or 1.                        
result = response.toString();
                        // res = res.trim();
                        result = result.replaceAll("\\s+", "");
                        // error.setText(res);

                        if (!result.equals("0")) {
                            SavePreferences("name", "pass", "emp_id", username
                                    .getText().toString(), password.getText()
                                    .toString());
                            Intent in = new Intent(Login.this, MainScreen.class);

                            // LoadPreferences();
                            error.setText("");

                            startActivity(in);
                        }

                        else
                            error.setText("Incorrect Username or Password");

                    } catch (Exception e) {
                        // un.setText(e.toString());
                    }

                }

CustomHttpClient.java

public class CustomHttpClient {
    /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. MySQL:SyntaxError:Nieoczekiwany identyfikator

  2. 2 sposoby konwersji liczby na ósemkową w MySQL

  3. Format wiersza MySQL:różnica między stałym a dynamicznym?

  4. Uruchamianie sum dla wielu kategorii w MySQL

  5. Błąd składni spowodowany użyciem zastrzeżonego słowa jako nazwy tabeli lub kolumny w MySQL