java - Passing ID with PHP and MySQL

142

I am programming an app where a teacher logs in with a username and password. After the login a new fragment in the app opens where the teacher sees all his students in aListView. To login I only type the username and the password. I use for this php and mysql.

My problem is that mylogin.php doesn't pass the ID from the teacher to theget_data.php where I do a SQL query.

login.php

<?php
session_start();
if($_SERVER['REQUEST_METHOD']=='POST'){
    $username = $_POST['username'];
    $password = $_POST['password'];       
    if($username == '' || $password == ''){
        echo '';
    }else{
        require_once('dbConnect.php');
        $sql = "SELECT ID_Teacher, username, password FROM Lehrer WHERE username='$username' and password='$password'";
        mysqli_error($con);
        $check = mysqli_fetch_array(mysqli_query($con,$sql));                    
    }
    if(isset($check)){
        echo "success";
        $_SESSION['id'] = $check['ID_Teacher'];
    }else{
        echo "Wrong Password or Username";
    }
}else{
    echo "Error, try again!";
}
?>

get_data.php

<?php
session_start();
require_once('dbConnect.php');
$sql = "SELECT Student.Name,Student.Surname FROM Student WHERE Student.ID_Teacher = {$_SESSION['id']}";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res))  
{  
    array_push($result, array('Name'=>$row[0], 'Surname'=>$row[1]));  
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>

ActivityLogin.java

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;

public class ActivityLogin extends AppCompatActivity implements View.OnClickListener{

public static final String USER_NAME = "USER_NAME";

public static final String PASSWORD = "PASSWORD";

private static final String LOGIN_URL = "http://bachelormedinf.16mb.com/login.php";

private EditText editTextUserName;
private EditText editTextPassword;

private Button buttonLogin;

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

    editTextUserName = (EditText) findViewById(R.id.username);
    editTextPassword = (EditText) findViewById(R.id.password);

    buttonLogin = (Button) findViewById(R.id.buttonUserLogin);

    buttonLogin.setOnClickListener(this);
}


private void login(){
    String username = editTextUserName.getText().toString().trim();
    String password = editTextPassword.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(ActivityLogin.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(ActivityLogin.this,ListView.class);
                intent.putExtra(USER_NAME,username);
                startActivity(intent);
            }else{
                Toast.makeText(ActivityLogin.this, s, Toast.LENGTH_LONG).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);

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

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

ListView.java

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class ListView extends ActionBarActivity implements View.OnClickListener {

private TextView textViewJSON;
private Button buttonGet;
private Button buttonParse;
private TextView textView;

public static final String MY_JSON ="MY_JSON";

private static final String JSON_URL = "http://www.bachelormedinf.16mb.com/get_data.php";

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

    textViewJSON = (TextView) findViewById(R.id.textViewJSON);
    textViewJSON.setMovementMethod(new ScrollingMovementMethod());
    buttonGet = (Button) findViewById(R.id.buttonGet);
    buttonParse = (Button) findViewById(R.id.buttonParse);
    buttonGet.setOnClickListener(this);
    buttonParse.setOnClickListener(this);

    textView = (TextView) findViewById(R.id.textViewUserName);

    Intent intent = getIntent();

    String username = intent.getStringExtra(ActivityLogin.USER_NAME);

    textView.setText("Willkommen Dr. " + username);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
    if(v==buttonGet){
        getJSON(JSON_URL);
    }

    if(v==buttonParse){
        showParseActivity();
    }
}

private void showParseActivity() {
    Intent intent = new Intent(this, ParseJSON.class);
    intent.putExtra(MY_JSON,textViewJSON.getText().toString());
    startActivity(intent);
}


private void getJSON(String url) {
    class GetJSON extends AsyncTask<String, Void, String>{
        ProgressDialog loading;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(ListView.this, "Please Wait...",null,true,true);
        }

        @Override
        protected String doInBackground(String... params) {

            String uri = params[0];

            BufferedReader bufferedReader = null;
            try {
                URL url = new URL(uri);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();

                bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                String json;
                while((json = bufferedReader.readLine())!= null){
                        sb.append(json+"\n");
                }

                return sb.toString().trim();

            }catch(Exception e){
                return null;
            }

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            textViewJSON.setText(s);
        }
    }
    GetJSON gj = new GetJSON();
    gj.execute(url);
}}

RegisterUserClass.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;


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();
}
}
878

Answer

Solution:

try this

  $sql = "SELECT Student.Name,Student.Surname FROM Student WHERE Student.ID_Teacher = ".$_SESSION['id'];

People are also looking for solutions to the problem: javascript - Animate progress Bar on execution of PHP script using JQuery

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.