首页 > 解决方案 > 将值发布到 php 文件以执行 sql 查询并以 json 格式取回数据

问题描述

我正在学习 Flutter 并尝试构建一个可以显示我今天的课程的移动应用程序。我想了解更多关于数据处理的知识,所以我尝试使用 php 并从数据库中获取数据。

我的目标是我想将日期值发布到 php 文件中,然后执行 sql 查询并获取 json 格式的数据。最后,数据将显示在 Flutter 应用程序中。

我的 php 文件的一部分如下:

$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);

用于从服务器获取数据的 apiProvider.dart 文件。

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.');
    }
  }
}

运行 Flutter 应用时无法显示课程数据。我认为“今天”值无法正确解析为 php 文件。我已经完成了谷歌搜索并尝试了不同的方法,但仍然无法正常工作。我不太明白如何处理 POST 方法。那么任何人都可以给我一些提示或建议来解决这个问题吗?谢谢。

=========== 更新 ==========

我已经通过使用Ephenodrom的方法解决了我的问题。更新的 dart 文件如下:

class ApiProvider {
...
  Future<CourseListModel> getCourses() async {

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

谢谢大家 :D

标签: phpflutterdart

解决方案


扑:

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());

?>

这就是您可以向服务器发送 GET 请求并在响应中获取 Json 数据的方式。

如果您使用本地服务器(例如 wamp),则转到 wamp 的配置并更改权限,以便它允许从自身访问(即 localhost)。


推荐阅读