0

I have a code where the user sends data to the database, this data include time. Im trying to set the script to prevent the user to send data only once every 30 minutes. Here is the code that I try but it doesnt work.

if($_SERVER['REQUEST_METHOD']=='POST'){

   $username = $_POST['username'];
   $points= $_POST['points'];
   $date= $_POST['date'];

$data = "SELECT date FROM tracker WHERE (username ='$username' ORDER BY date DESC LIMIT 1)";


$data_result = $connect->query($data);
$re = $data_result->fetch_assoc();

if($re["date"] <= strtotime('-30 minute')){

echo '0';

}}
LoveDroid
  • 75
  • 1
  • 10
  • Those parenthesis in the query are unnecessary and confusing at best, and I'd be surprised if MySQL even allowed that query. – Uueerdo Jun 01 '18 at 23:20
  • **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or **any** user data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Jun 02 '18 at 03:08
  • @Uueerdo Yeah, you can add parens around conditions, but not around the `ORDER BY` and `LIMIT` parts. This should be coughing up errors. A lot of problems can be detected and resolved by [enabling exceptions in `mysqli`](https://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) so mistakes aren't easily ignored. – tadman Jun 02 '18 at 03:08
  • Thank you everybody, Im still find hard time to fetch date from the database, anybody can suggest other way to fetch date – LoveDroid Jun 02 '18 at 03:20

1 Answers1

1

You can calculate difference of current datetime with last datetime as

SELECT TIMESTAMPDIFF(MINUTE, date, now()) as mins FROM tracker WHERE username ='$username' ORDER BY date DESC LIMIT 1

Make sure that data type of date column should be datetime

Mesar ali
  • 1,832
  • 2
  • 16
  • 18