How to display MySQL query results based on TextField value entered

1.7k Views Asked by At

I am fairly new to Flutter and would like to find out how to display MySQL query results based on the TextField value entered by user.

As I am new to Flutter I scraped bits and pieces from other Tutorials to try and achieve outcome .

Some help would be tremendously grateful for , as I am struggling for weeks now with this.This is a re-edit on my question as I am trying to be bit more descriptive hoping someone can pleeeease help . Thank you

This is my MySQL table : My MySQL table

This my PHP file (flutter_data.PHP)

$con = mysqli_connect($HostName, $HostUser, $HostPass, $DatabaseName);

$json = file_get_contents('php://input'); 

$obj = json_decode($json,true);

$name = $obj['name'];//this value coming from TextField ( i hope :-)) 

$CheckSQL = "SELECT * FROM Student_data WHERE student_name = '$name'";

$result = $con->query($CheckSQL);

if ($result->num_rows >0) {

 while($row[] = $result->fetch_assoc()) {

 $Item = $row;

 $json = json_encode($Item, JSON_NUMERIC_CHECK);

 }

}else {

 echo "No Results Found.";

}

echo $json;

$con->close();
?>

I did a test to see if my PHP file works without the WHERE clause . Below running my PHP file .

enter image description here

My Home screen consisting of TextField , Image , FlatButton

enter image description here

Setting Class variables:


 int studentID;
 String studentName;
 int studentPhoneNumber;
 String studentSubject;

  Studentdata({
    this.studentID,
    this.studentName,
    this.studentPhoneNumber,
    this.studentSubject
  });

  factory Studentdata.fromJson(Map<String, dynamic> json) {
    return Studentdata(
      studentID: json['id'],
      studentName: json['student_name'],
      studentPhoneNumber: json['student_phone_number'],
      studentSubject: json['student_class']

    );
  }
}

I have set my TextField to capture onChanged value

 onChanged: (value) {

                setState(() {

                    name = value;

My FlatButton with onPressed :

onPressed: () {


                  var route = new MaterialPageRoute(

                    builder: (BuildContext context) => new NextPageState(name.toString(),                           


                  ));
                  Navigator.of(context).push(route);
                },

Below code for NextPage :

class NextPageState extends StatefulWidget {

  final String name;

  NextPageState(this.name);

  @override

  State<StatefulWidget> createState() {

    return NextPage(this.name);

  }
}

class NextPage extends State<NextPageState> {

  final String name ;

  NextPage(this.name);

  // API URL
  var url = 'https://www.datashine.co.za/flutter_data.php';

  Future<List<Studentdata>> fetchStudent() async {

    var data = {'name': name};

    var response = await http.post(url, body: json.encode(data));

    if (response.statusCode == 200) {

      print(response.statusCode);

      final items = json.decode(response.body).cast<Map<String, dynamic>>();

      List<Studentdata> studentList = items.map<Studentdata>((json) {
        return Studentdata.fromJson(json);
      }).toList();

      return studentList;

      }

    else {
      throw Exception('Failed to load data from Server.');
    }
  }

  @override
Widget build(BuildContext context) {
  return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(name),
          automaticallyImplyLeading: true,
          leading: IconButton(icon:Icon(Icons.arrow_back),
          onPressed:() => Navigator.pop(context, false),
        )
      ),
      body: FutureBuilder<List<Studentdata>>(
      future: fetchStudent(),
      builder: (context, snapshot) {

      if (!snapshot.hasData) return Center(
        child: CircularProgressIndicator()
      );

        return ListView(
      children: snapshot.data
      .map((data) => Column(children: <Widget>[

        GestureDetector(
          onTap: (){print(data.studentName);},
          child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [

          Padding(
          padding: EdgeInsets.fromLTRB(0, 20, 0, 10),
          child: Text('Name = ' + data.studentName.toString(),
            style: TextStyle(fontSize: 21))),



                  ]),)
                 ],))
           .toList(),
              );
             },
            )
          ));
         }
        }

Upon running App , it seems like no results are returning . So I have no idea on how to fix . The Circularprogress indicator just loads and hangs .

enter image description here

0

There are 0 best solutions below