所以我将 PHP slimframework ( https://www.slimframework.com/ ) 用于我需要在我的 React 应用程序中使用的简单 API,但我无法让我的查询使用这些参数,因为 $start_date 和 $end_date 没有从获取请求。这个 MySQL 查询正常工作,我已经用 startDate 和 endDate 测试了它,我从我的 React 应用程序返回,问题是我无法弄清楚如何从这些 GET 请求中将数据返回到我的 $start_date 和 $end_date 变量.
这是我的后端(slimframework)的样子:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
$app->get('/api/date', function(Request $request, Response $response){
$start_date=date('Y-m-d H:i:s', $_GET['startDate']);
$end_date=date('Y-m-d H:i:s', $_GET['endDate']);
// $start_date = $app->request()->params('startDate');
// $end_date = $app->request()->params('endDate');
// $start_date = $request->getAttribute['startDate'];
// $end_date = $request->getAttribute('endDate');
$sql = "SELECT * FROM `datescalendar` where `date` BETWEEN '{$start_date}' AND '{$end_date}'";
// $sql = "SELECT * FROM `datescalendar` where `date` BETWEEN '1525679047' AND '1526283847'";
try{
// Get DB Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->query($sql);
$dates = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
// return $response->withJson($dates);
echo json_encode($dates);
} catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
});
这就是我在 React 应用程序中从 API 获取数据的方式:
fetchNewDatesNext() {
const startDate = this.state.startDate.unix();
const endDate = this.state.startDate.add(1, 'week').unix();
axios.get(`http://localhost/api/date?startDate=${startDate}&endDate=${endDate}`).then((response) => {
this.setState(() => ({ data: response.data}));
});
};
当我一次从数据库查询所有内容时,应用程序正常工作 ($sql = "SELECT * FROM datescalendar
)
有什么想法吗?
最佳答案
$startDate = $request->getQueryParam('startDate');
$endDate = $request->getQueryParam('endDate');
还要注意那个查询,它容易受到 SQL 注入(inject)的攻击。您必须使用准备好的语句。参见 https://phpdelusions.net/pdo#prepared
关于PHP slimframework GET 请求不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50220386/