So I am using PHP slimframework (https://www.slimframework.com/) for just a simple API I need to use in my React application and I cannot get my query to work with these parameters, because $start_date and $end_date are not returning anything from GET request. This MySQL query works like it should, I already tested it with startDate and endDate I get back from my React app, the problem is that I cannot figure it out how to get data back from these GET requests to my $start_date and $end_date variables.
This is what my backend looks like (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().'}';
}
});
This is how I fetch data from API in my React app:
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}));
});
};
Application is working like it should when I just query everything at once from database ($sql = "SELECT * FROM datescalendar
)
Any ideas?
$startDate = $request->getQueryParam('startDate');
$endDate = $request->getQueryParam('endDate');
Also watch out with that query, it is vulnerable to SQL injection. You must use prepared statements. See https://phpdelusions.net/pdo#prepared