0

I'm trying to delete a row in my table after 1 minute (for test) since it was inserted. In MySql, I found a way to do this, but it is not working.

The code:

// starting and getting the session ID
session_start();
$session = session_id();

// get the timestamp
$date = date_create();
$time = date_timestamp_get($date);

// create the timestamp with the variation of 1 minute
$time_check = $time + 1;

// inserting the session ID with the current time
$sql1 = "INSERT INTO $tbl_name(session, time) VALUES ('$session', '$time')"; 
$connect->query($sql1);

Until know, everything works fine. After the code above, I'm trying the delete thing:

$sql2 = "DELETE FROM $tbl_name WHERE time < $time_check";
$connect->query($sql2);

I saw another approach in a tutorial (see it here). I was trying to understand the code above and also trying to see another option, like creating an event with MySql:

$sql2 = "CREATE EVENT clearSession
            ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 MINUTE
            DO DELETE FROM $tbl_name where session = $session";
$connect->query($sql2);

I would like to know where is the mistake.

Italo Borges
  • 2,355
  • 5
  • 34
  • 45
  • 3
    **WARNING**: This has some severe [SQL injection bugs](http://bobby-tables.com/) because `$_GET` data is used inside the query. Whenever possible use **prepared statements**. These are quite straightforward to do in [`mysqli`](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [PDO](http://php.net/manual/en/pdo.prepared-statements.php) where any user-supplied data is specified with a `?` or `:name` indicator that’s later populated using `bind_param` or `execute` depending on which one you’re using. – tadman Nov 03 '16 at 18:57
  • 1
    @tadman, thanks for the tip, I'm going to change the code. – Italo Borges Nov 03 '16 at 19:05
  • Events have nothing to do with PHP or any such language. You need to activate them. They need to be on a schedule. They need to be `PRESERVE` 'd, etc – Drew Nov 03 '16 at 19:08
  • Yes, but I'm asking if something is wrong in my code. I know that it has nothing to do with PHP. I just need to know if I'm using right. – Italo Borges Nov 03 '16 at 19:50
  • just come to the [Campaigns](http://chat.stackoverflow.com/rooms/95290) chat room and I will be glad to help. Just ping me with an @ sign. – Drew Nov 05 '16 at 01:55

0 Answers0