首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将从MySQL派生的数据从一个PHP移动到另一个

问将从MySQL派生的数据从一个PHP移动到另一个
EN

Stack Overflow用户
提问于 2015-02-18 14:37:02
回答 2查看 103关注 0票数 0

我正在创建一个Android应用程序,其中我有一个登录页面,然后一个页面显示基于谁登录的数据。

登录页面如下:

代码语言:javascript
复制
    <?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";  
    }
    ?>

我的列表页面是:

代码语言:javascript
复制
<?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(“从雇员中选择*);

应该是这样的

$result =mysql_query(“Group_ID =‘.$userid.”);

其中,$userid来自登录PHP页面并发送到列表视图页。

因此,基本上如何从登录到listview的用户那里发送Group_ID?我只想显示与登录用户具有相同Group_ID的员工。

下面是代码的Android端:

登录视图:

代码语言:javascript
复制
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页):

阿普科克托:

代码语言:javascript
复制
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;


    }


}

实际列表查看页:

代码语言:javascript
复制
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);



        }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-18 15:38:42

在您的第一个登录文件中,添加此代码,以便将group_id放入session var:

代码语言:javascript
复制
$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'];
}

在第二种情况下,你可以做这样的事情:

代码语言:javascript
复制
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中处理

因此,在登录视图中,您可以更改:

HttpClient httpclient;

至

public static DefaultHttpClient httpclient;

在上颈项改变中:

代码语言:javascript
复制
DefaultHttpClient httpClient = new DefaultHttpClient();  // Default HttpClient
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);

至:

代码语言:javascript
复制
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = LoginPage.httpClient.execute(httpGet);
票数 0
EN

Stack Overflow用户

发布于 2015-02-18 15:05:27

我不知道你的数据库是怎么来的,试试这个:

代码语言:javascript
复制
    <?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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28586230

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档