1

I try to make page of user login to my app. page is work now but I need to do same thing also.I need to select all data of this user if user login correct.

I use this code to login:

     var url = 'http://xxxxxxxx/login_user.php';
      var data = {'email': email, 'password' : password};
      var response = await http.post(url, body: json.encode(data));
      var message = jsonDecode(response.body);
       print("tapped ${data}");
      if(message == 'Login Matched')

      {
        setState(() {
          visible = false;


        });

        Navigator.push(context, MaterialPageRoute(builder: (context) => mainpage(email : emailController.text)));
      }else{
        setState(() {
          visible = false;

        });


<?php
include 'connt.php';
 
 $json = file_get_contents('php://input');
 $obj = json_decode($json,true);
 $email = $obj['email'];
 $password = $obj['password'];
 $loginQuery = "select * from user_registration where email = '$email' and password = '$password' ";
 $check = mysqli_fetch_array(mysqli_query($con,$loginQuery));
    if(isset($check)){
         $onLoginSuccess = 'Login Matched';
         $SuccessMSG = json_encode($onLoginSuccess);
         echo $SuccessMSG ; 
     }
    
     else{
    
        $InvalidMSG = 'Invalid Username or Password Please Try Again' ;
        $InvalidMSGJSon = json_encode($InvalidMSG);
         echo $InvalidMSGJSon ;
     
     }
 
 mysqli_close($con);
?>

I have in my table different fields as lastname , age , tell..'

I need to select all fields.Now if I try to see data by this code:

 print("tapped ${data}");

just I have email and password.So if anyone have idea how can i do that please help me.

full code


import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:onefrist/main.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'MyPreferences.dart';
import 'main.dart';
import 'Registration.dart';


void main() => runApp(loginpage());

var id;
class loginpage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
                backgroundColor: Colors.amber,
                title: Text('User Login Form')),
            body: Center(
                child: LoginUser()
            )
        )
    );
  }
}

class LoginUser extends StatefulWidget {
  LoginUserState createState() => LoginUserState();

}

class LoginUserState extends State <LoginUser>{
  MyPreferences _myPreferences = MyPreferences();


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _myPreferences.init().then((value) {
      setState(() {
        _myPreferences = value;
        check_if_already_login();
      });
    });
  }



  void check_if_already_login() async {
   if (_myPreferences.password !=null && _myPreferences.user !=null) {
      Navigator.pushReplacement(
          context, new MaterialPageRoute(builder: (context) =>mainpage ()));
   }else{

   }
  }

  bool visible = false ;
  Future userLogin() async{
    setState(() {
      visible = true ;

    });

    final emailController = TextEditingController(text: _myPreferences.user);
    final passwordController = TextEditingController(text: _myPreferences.password);
   // final idController = TextEditingController();
    // Getting value from Controller
    String email = emailController.text;
    String password = passwordController.text;
   // String id = idController.text;
    if(email == '' || password == '')
    {
      // Put your code here which you want to execute when Text Field is Empty.
      print('Text Field is empty, Please Fill All Data');
    }else{

      var url = 'http://192.168.8.105/login_user.php';
      var data = {'email': email, 'password' : password};
      var response = await http.post(url, body: json.encode(data));
      var message = jsonDecode(response.body);
       print("tapped ${data}");
      if(message == 'Login Matched')

      {
        setState(() {
          visible = false;


        });

        Navigator.push(context, MaterialPageRoute(builder: (context) => mainpage(email : emailController.text)));
      }else{
        setState(() {
          visible = false;

        });

        // Showing Alert Dialog with Response JSON Message.
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: new Text(message),
              actions: <Widget>[
                FlatButton(
                  child: new Text("OK"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );}
    }
  }

  @override
  Widget build(BuildContext context) {
    final emailController = TextEditingController(text: _myPreferences.user);
    final passwordController = TextEditingController(text: _myPreferences.password);
    final idController = TextEditingController();
    return Scaffold(
        body: SingleChildScrollView(
            child: Center(
              child: Column(
                children: <Widget>[

                  Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Text('User Login Form',
                          style: TextStyle(fontSize: 21))),

                  Divider(),

                  Container(
                      width: 280,
                      padding: EdgeInsets.all(10.0),
                      child: TextField(
                        controller: emailController,
                        onChanged: (value) {
                          _myPreferences.user = value;
                          _myPreferences.commit();
                        },
                        autocorrect: true,
                        decoration: InputDecoration(hintText: 'Enter Your Email Here'),
                      )
                  ),

                  Container(
                      width: 280,
                      padding: EdgeInsets.all(10.0),
                      child: TextField(
                        controller: passwordController,
                        onChanged: (value) {
                          _myPreferences.password = value;
                          _myPreferences.commit();
                        },
                        autocorrect: true,
                        obscureText: true,
                        decoration: InputDecoration(hintText: 'Enter Your Password Here'),
                      )
                  ),
                  Container(
                      width: 280,
                      padding: EdgeInsets.all(10.0),
                      child: TextField(
                        controller: idController,
                        autocorrect: true,
                        decoration: InputDecoration(hintText: 'Enter Your Password Here'),
                      )
                  ),
                  RaisedButton(
                    onPressed: userLogin,
                    color: Colors.green,
                    textColor: Colors.white,
                    padding: EdgeInsets.fromLTRB(9, 9, 9, 9),
                    child: Text('Click Here To Login'),

                  ),
                  FlatButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    disabledColor: Colors.grey,
                    disabledTextColor: Colors.black,
                    padding: EdgeInsets.all(8.0),
                    splashColor: Colors.blueAccent,
                    onPressed: () {
                      Navigator.push(context, MaterialPageRoute(builder: (context) => RegisterUser()
                      ),);
                    },
                    child: Text(
                      "Reistraion page",
                      style: TextStyle(fontSize: 20.0),
                    ),
                  ),
                  Visibility(
                      visible: visible,
                      child: Container(
                          margin: EdgeInsets.only(bottom: 30),
                          child: CircularProgressIndicator()
                      )
                  ),
                ],
              ),
            )));
  }

}



  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Aug 15 '20 at 13:17
  • 1
    **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Aug 15 '20 at 13:17

1 Answers1

0

Yes. You can have only email and password if you print data.
Consider print(message).
This can show the data which is received from the server! Also in your server, consider sending all data as a response.

$check = mysqli_fetch_array(mysqli_query($con,$loginQuery));
if($check){
     $check['password'] = '';
    // Make sure you are not returning the password for security reasons!
     $check['result'] = 'Login Matched';
     $SuccessMSG = json_encode($check);
     echo $SuccessMSG ; 
 }

 else{
    $InvalidMSG= array("result"=>"Invalid Username or Password Please Try Again");
    $InvalidMSGJSon = json_encode($InvalidMSG);
     echo $InvalidMSGJSon ;
 
 }

In your dart code, you could simply do this.

if(message['result'] == 'Login Matched')
{
  // Do Something
}else{
  // Do Something
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Shri Hari L
  • 4,551
  • 2
  • 6
  • 18
  • Hi brother .Thank you, it works, yes now, but I have how can I take only one field? Because now I see all fields for the user and I only need to take the id –  Aug 15 '20 at 09:04
  • I make print(message) now and I see all data of user I just need to take id –  Aug 15 '20 at 09:05
  • 1
    Try using `message['your column name']`. in your case, `message['id']`. – Shri Hari L Aug 15 '20 at 09:10