我正在创建一个Android应用,其中我有一个登录页面,然后是一个显示基于谁登录的数据的页面。
登录页面如下:
<?php
include('listview.php');
$hostname_localhost ="URL";
$database_localhost ="project_test";
$username_localhost ="user";
$password_localhost ="pass";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from Employee where Emp_Email = '".$username."' AND Emp_Password = '".$password. "'";
$userid = mysql_query("SELECT Group_ID FROM Employee where Emp_Email = '".$username."' AND Emp_Password = '".$password. "'");
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if(($rows == 0) || ($username == NULL)) {
echo "No Such User Found";
}
else {
echo "User Found";
}
?>
我的listview页面是:
<?php
$con = $con = mysql_connect("URL","user","pass");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("project_nfc", $con);
$result = mysql_query("SELECT * FROM Employee");
while($row = mysql_fetch_assoc($result)) { $output[]=$row; }
print(json_encode($output));
mysql_close($con);
?>
在变量$ result中,我试图仅显示与登录人员具有相同GroupID的员工。
所以:
$ result = mysql_query(“SELECT * FROM Employee);
应该像
$ result = mysql_query(“SELECT * FROM Employee where Group_ID ='”。$ userid。“'”);
其中$ userid派生自登录PHP页面并发送到列表视图页面。
那么基本上如何从登录列表视图的用户发送Group_ID?我只想显示与登录用户具有相同Group_ID的员工。
以下是代码的Android方面:
登录视图:
package dbtesting.example.com.testexternaldb;
import android.app.Activity;
import org.apache.http.client.ResponseHandler;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class LoginPage extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.username);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(LoginPage.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://URL/Android/check.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(LoginPage.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(LoginPage.this, MainActivity.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
LoginPage.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginPage.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
列表视图(2页):
Apiconector:
package dbtesting.example.com.testexternaldb;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
public class ApiConnector {
public JSONArray GetAllCustomers()
{
// URL for getting all customers
String url = "http://URL/Android/listview.php";
// Get HttpResponse Object from url.
// Get HttpEntity from Http Response Object
HttpEntity httpEntity = null;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
// Signals error in http protocol
e.printStackTrace();
//Log Errors Here
} catch (IOException e) {
e.printStackTrace();
}
// Convert HttpEntity into JSON Array
JSONArray jsonArray = null;
if (httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonArray;
}
}
实际listviewpage:
package dbtesting.example.com.testexternaldb;
import android.app.Activity;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends ActionBarActivity {
private ListView GetAllCustomerListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.GetAllCustomerListView = (ListView) this.findViewById(R.id.GetAllCustomerListView);
new GetAllCustomerTask().execute(new ApiConnector());
}
private void setListAdapter(JSONArray jsonArray)
{
this.GetAllCustomerListView.setAdapter(new GetAllCustomerListViewAdapter(jsonArray,this));
}
private class GetAllCustomerTask extends AsyncTask<ApiConnector,Long,JSONArray>
{
@Override
protected JSONArray doInBackground(ApiConnector... params) {
// it is executed on Background thread
return params[0].GetAllCustomers();
}
@Override
protected void onPostExecute(JSONArray jsonArray) {
setListAdapter(jsonArray);
}
}
}
答案 0 :(得分:0)
我不知道你的DB如何,试试这个:
<?php
$con = $con = mysql_connect("URL","user","pass");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("project_nfc", $con);
$result = mysql_query("SELECT * FROM Employee where id_group=".$id_group." ");
while($row = mysql_fetch_assoc($result)) { $output[]=$row; }
print(json_encode($output));
mysql_close($con);
?>
确保您有一个列名 id_group 并且变量 $ id_group
答案 1 :(得分:0)
在您的第一个登录文件中添加此代码,以便将group_id放入session var:
$userid = mysql_query("SELECT Group_ID FROM Employee where Emp_Email = '".$username."' AND Emp_Password = '".$password. "'");
if ($row = mysql_fetch_assoc($userid)) {
session_start();
$_SESSION['group_id'] = $row['Group_ID'];
}
在第二个中,您可以执行以下操作:
session_start();
if (isset($_SESSION['group_id'])) {
$result = mysql_query("SELECT * FROM Employee where group_id=".$_SESSION['group_id']." ");
}else{
$result = mysql_query("SELECT * FROM Employee");
}
但是请停止使用mysql_
它已被弃用,将开发转换为PDO或mysqli
以下链接指向如何处理java for Android中的会话https://stackoverflow.com/a/6054828/4421474
所以在您的登录视图中,您可以更改:
HttpClient httpclient;
到
public static DefaultHttpClient httpclient;
并在apiconnector中更改:
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
为:
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = LoginPage.httpClient.execute(httpGet);