Hi guys, I really need your help. 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 see all his students in a ListView. To Login I only type the username and the password . I use for this php and mysql. My problem is that my login.php don't pass the ID from the teacher to the get_data.php where I do a SQL query. I just started with programming so please be patient.

My login.php:

<?php
        session_start();
    if($_SERVER['REQUEST_METHOD']=='POST'){

                $username = $_POST['username'];
        $password = $_POST['password']; 
                $Teacher_ID= $_GET['Teacher_ID'];


        if($username == '' || $password == ''){
            echo '';
        }else{
        require_once('dbConnect.php');

                $sql = "SELECT ID_Teacher, username, password FROM Teacher WHERE username='$username' and password='$password'";


                $check = mysqli_fetch_array(mysqli_query($con,$sql));


        }
        if(isset($check)){


            echo "succes";
        }else{
            echo "wrong username or password";
        }

    }else{
        echo "error try again";
    }

My get_data.php:

<?php
session_start();
require_once('dbConnect.php');
$_GET['Lehrer_ID'] = $id;


$sql = "SELECT Student.Name,Student.Surname FROM Student WHERE Student.ID_Teacher = .$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);

?>

Recommended Answers

All 16 Replies

Member Avatar for diafol
$_GET['Lehrer_ID'] = $id;

Is the wrong way around, should be?

$id = $_GET['Lehrer_ID'];

Anyhow, you should store the logged in user_id in a session variable, e.g. $_SESSION['id']

Be aware that your current code leaves you wide open to SQL injection as you are not sanitizing your user input variables ($_POST) neither are you using prepared statements.

See my recent tute: DW Tutorial: Common Issues with MySQL and PHP

login.php -->So instead of

$Teacher_ID= $_GET['Teacher_ID']; 

should I write ?

$_SESSION['Teacher_ID'];

But what should I write in get_data.php do get the ID from the Teacher from login.php?

Member Avatar for diafol

There are quite a few things with this script that require attention:

You place unsanitized user input vars directly in the SQL (open to SQL injection) - see see my tutorial (link in previous post) for a section on this (#2. SQL Injection: What to do with $_POST and $_GET variables):

 $sql = "SELECT ID_Teacher, username, password FROM Teacher WHERE username='$username' and password='$password'";

The password field is plaintext not hashed. This is very dangerous. Have a look at the password_verify() and password_hash() functions - or see my tutorial for a section on this (#11. Storing and Retrieving Authentication Data).

On this...

 if(isset($check)){
            echo "succes";

Add the user id to the session superglobal array ($_SESSION):

if(isset($check)){
            echo "succes";
            $_SESSION['id'] = $check['ID_Teacher'];

The logged in teacher is now safely entered (via ID) in the session. So now you can have something like:

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

(Not sure where you were getting $_GET from). Although, when dynamic data is inserted into a statement, I always use a prepared statement rather than a query. See tutorial (#4. What to do With Dynamic Values?)

Thx man :) when I check with var_dump($_SESSION['id']); in my login.php data it gives me back the ID from the Teacher. But unfortunately when I check it on get_data.php then it seems to be that it don't recieve the ID. I post my get_data.php maybe I did something wrong. I will change the code later and secure it agains sql injection.

<?php
    session_start();
    require_once('dbConnect.php');
    $_SESSION['id'] = $check['ID_Lehrer'];
    $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);
    ?>
Member Avatar for diafol

Why $_SESSION['id'] = $check['ID_Lehrer']; in this page? You should have done that already in the login page. $check['ID_Lehrer'] does not exist in this page. Just take out line 4.

I already tried this. But then I get an error

<br/>
<b>Warning</b>: mysqli_fetch_array() excepts parameter 1
to be mysli_result, boolean given in <b>/home/u88870/
public_html/get_data.php</b> on line<b>10</b>

which means it is this line while($row = mysqli_fetch_array($res)) but I don't get why? Do you have an idea?

Member Avatar for diafol

Mean $res is not a resource. Your query failed and returned 'false'. Could be a number of things. Do a die() to find out:

$res = mysqli_query($con, $sql) or die(mysql_error());
while($row = mysql_fetch_array($res))
{
   ...
}

I checked it and the problem is that the get__data.php file is not getting the ID. In the query it shows NULL. That is the reason why it returns false. Did I start the session wrong or forgot something?

Member Avatar for diafol

Show the updated code for both pages.

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_Lehrer, username, password FROM Lehrer WHERE username='$username' and password='$password'";

        echo mysql_error();

        $check = mysqli_fetch_array(mysqli_query($con,$sql));                    
        }
        if(isset($check)){

            echo "success";
            $_SESSION['id'] = $check['ID_Lehrer'];

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

?>
Member Avatar for diafol

Are you getting 'succes' from the login script? As long as every page you go to before get_data has a session_start() then the 'id' will be stored in the session.

No I don't get the echo "success" but I can still login but I remember that that in the past it appeared when I logged in. I will check it. Do you think that it could be the reason?

Member Avatar for diafol

If you are not logging in and getting the 'success' message, then you are not logging in - from your code, you are not entering the successful branch of your conditional construct:

if(isset($check)){
        echo "success";
        $_SESSION['id'] = $check['ID_Lehrer'];
    }else{
        echo "Wrong Password or Username";
    }

Which msg are you getting?
Try if($check) instead of if(isset($check))

No that doesn't change anything. I rember now why it didn't appear because I made it not to appear on the screen in my java code. Maybe there is something wrong with my java code.

ActivityLogin.java

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://baxxxxxx.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

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.baxxxxxxx.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);
    }
}
Member Avatar for diafol

Not my scene. Anybody else?

Do I have to work with JOINS ?? Would that solve the problem?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.