简体   繁体   中英

Post value to a php file to execute sql query and get back data in json format

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

flutter:

http.get('http://project.php?date=today');

php :

<?php

function fetchDataa(){
   include 'connect.php';

   $date = $_GET['date'];

   $conn = connect();
   $sql = 'SELECT * FROM areas Where date = $date';
   $result = mysqli_query($conn, $sql);

   $i=0;
   if (mysqli_num_rows($result) > 0) {
      while($row = mysqli_fetch_assoc($result)) {
         $arrA[$i]=array('area_id'=>$row['id'], 'name' => $row['name']);
         $i++;
      }

   } else {
      echo "0 results";
   }
   $conn->close();
   return json_encode($arrA);
}

print_r(fetchDataa());

?>

This is how you can send a GET request to your server and the get the Json data in the response.

If you use a local server (eg, wamp) then go to wamp's configuration and change the permission so that it permits access from itself (ie, localhost).

Your Problem

You make a POST request and after that you make a GET request. Your should get the response from your php script within the POST request. It is not necessary to make a GET request after that .

Change this :


http.post(apiURL, body: {"date": today});
final response = await client.get(apiURL);

To this :


final response = http.post(apiURL, body: {"date": today});

I would highly recommend to check out the information below!

Additional Information

There is a dart package that provides some helper classes for http requests.

Github : https://github.com/Ephenodrom/Dart-Basic-Utils Install it with:

dependencies:
  basic_utils: ^1.5.1

Usage

Map<String, String> headers = {
  "Some": "Header"
};
Map<String, String> queryParameters = {
  "Some": "Parameter"
};

String url = "";
String payloadAsString = "{\"date\": \"2019-06-18\"}";

Future<CourseListModel> getCourses() async {

    Map<String, dynamic> body;
    try {
        body = await HttpUtils.postForJson(url, payloadAsString,
        queryParameters: queryParameters, headers: headers);
    } catch (e) {
        // Handle exception, for example if response status code != 200-299
    }
    return CourseListModel.fromJson(body);
}

Additional information :

These are all methods from the HttpUtils class.

Future<Map<Response> getForFullResponse(String url,{Map<String, dynamic> queryParameters,Map<String, String> headers});
Future<Map<String, dynamic>> getForJson(String url,{Map<String, dynamic> queryParameters,Map<String, String> headers});
Future<String> getForString(String url,{Map<String, dynamic> queryParameters,Map<String, String> headers});
Future<Map<Response> postForFullResponse(String url, String body,{Map<String, String> queryParameters,Map<String, String> headers});
Future<Map<String, dynamic>> postForJson(String url, String body,{Map<String, String> queryParameters,Map<String, String> headers});
Future<String> postForString(String url, String body,{Map<String, String> queryParameters,Map<String, String> headers});
Future<Response> putForFullResponse(String url, String body,{Map<String, String> queryParameters,Map<String, String> headers});
Future<Map<String, dynamic>> putForJson(String url, String body,{Map<String, String> queryParameters,Map<String, String> headers});
Future<String> putForString(String url, String body,{Map<String, String> queryParameters,Map<String, String> headers});
Future<Response deleteForFullResponse(String url,{Map<String, String> queryParameters,Map<String, String> headers});
Future<Map<String, dynamic>> deleteForJson(String url,{Map<String, String> queryParameters,Map<String, String> headers});
Future<String> deleteForString(String url,{Map<String, String> queryParameters,Map<String, String> headers});
Map<String, dynamic> getQueryParameterFromUrl(String url);
String addQueryParameterToUrl(String url, Map<String, dynamic> queryParameters);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM