I’m currently working on a Flutter project with php mysql as the backend. Is there anyway that I could possibly fetch data directly from php file? I’m so clueless.
For example, how do I fetch $dept from php file below and display it in a widget or store the data in Flutter:
<?php session_start(); include_once ('config.php'); $lg_username = $_REQUEST['lg_username']; $lg_password = $_REQUEST['lg_password']; $lg_password = md5($lg_password); $sql = "SELECT lg_username, lg_name, lg_dp_code FROM hr_login WHERE lg_username = '$lg_username' AND lg_password = '$lg_password'"; $res = mysqli_query($conn,$sql); $userRow = mysqli_fetch_array($res,MYSQLI_ASSOC); $user = $userRow['lg_username']; $name = $userRow['lg_name']; $dept = $userRow['lg_dp_code']; $count = mysqli_num_rows($res); if($count == 1){ return $dept; }else{ echo json_encode("Error"); } ?>
Future _saveCheckIn()
Future _saveCheckIn() async { var url = Uri.http( "192.168.68.216", '/ump_attendance_2/save_check_in.php', {'q': '{http}'}); var response = await http.post(url, body: { "lg_username": user.lg_username, "lg_password": user.lg_password }); //call the string data from php file }
Thanks in advance.
Advertisement
Answer
You can use json_encode($dept) instead of $dept on the php side. After that, you can check data like below and return $dept data and use the futurebuilder.
Future _saveCheckIn() async { var url = Uri.http( "192.168.68.216", '/ump_attendance_2/save_check_in.php', {'q': '{http}'}); var response = await http.post(url, body: {"lg_username": user.lg_username, "lg_password": user.lg_password}); if (response.statusCode == 200) { return json.decode(response.body); } else { print('Something wents wrong'); } }
FutureBuilder( future: _saveCheckIn(), builder: (BuildContext context, AsyncSnapshot snapshot) { switch (snapshot.connectionState) { case ConnectionState.done: if (snapshot.hasData) { return Text(snapshot.data); } return const Text('What do you want'); default: return const Center( child: CircularProgressIndicator(), ); } }, )