I am learning Flutter and trying to build a mobile application that can display my today courses. And I want to learn more about data handling so I try to use php and get data from database.
My target is that I want to post the date value to the php file, then execute the sql query and get the data in json format. Finally, the data will be displayed in a Flutter app.
A part of my php file is as follow:
$date = $_POST["date"];
$sql = "SELECT * FROM Table WHERE Date = '$date'";
$response=array();
$final=array();
$response["status"] = "fail";
$result = mysqli_query($con, $sql);
while($row=mysqli_fetch_assoc($result)){
$response["status"] = "success";
$final[] = $row;
}
$response["result"]=$final;
echo json_encode($response);
The apiProvider.dart file to get data from the server.
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' show Client;
import 'package:http/http.dart' as http;
class ApiProvider {
Client client = Client();
final String apiURL = "my.php";
final String today = '2019-06-18';
// Use to fetch today courses.
Future<CourseListModel> getCourses() async {
http.post(apiURL, body: {"date": today});
final response = await client.get(apiURL);
if (response.statusCode == 200) {
// If the API call to the server was successful, parse the course list in JSON format
return CourseListModel.fromJson(json.decode(response.body));
}
else {
// If the API call was fail, throw an error.
throw Exception('Response content length is ${response.statusCode}, failed to get today courses.');
}
}
}
The course data cannot be shown when I run the Flutter app. I think the "today" value cannot be parse to the php file correctly. I have done Google search and tried different methods but it still not work. I am not quite understand how to handle the POST method. So can anyone give me some hints or suggestions to solve the problem? Thanks.
=========== Updated ==========
I have solved my problem by using the Ephenodrom's method. Updated dart file is as follow:
class ApiProvider {
...
Future<CourseListModel> getCourses() async {
final response = await http.post(apiURL, body:{"date": today});
...
}
Thanks everyone :D