Question

I have a database where entries are inserted into tables with a timestamp (an int from PHP's time() not an SQL timestamp). I want to make a query to drop all tables where the greatest timestamp is less than the expiry time (some time from the time the query is executed). Right now I have

$q = mysqli_query(..., "SHOW TABLES LIKE 'prefix%'");
if($q===FALSE) die(mysqli_error(...));
for($row in mysqli_fetch_array($q)){
    $slice = array_slice($row, 0, 1);
    $tbl = array_shift($slice);
    mysqli_query(..., "DROP TABLE `$tbl` WHERE ((SELECT GREATEST (SELECT `time` FROM `$tbl`)) <= $expiry_time)");
}

This gives an SQL syntax error.

What is the correct way to achieve this? Also, is it possible to eliminate the PHP logic and just loop through each table and drop it if necessary all in SQL?

Was it helpful?

Solution

The approach you've tried will not work - you're mixing data definition statements with data manipulation statements.

You could probably do it in a stored procedure in MySQL, but I haven't tried it.

So you're faced with a choice: do it in MySQL via a stored procedure (which, to my mind, kind of hides the implementation) or do it in PHP (where the code will probably be more accessible and understandable).

Note that, in either event, you'll probably need to lock the tables to prevent the table from disappearing between the time when you query it (to find the timestamp value) and the time when you drop it.

OTHER TIPS

I don't think the answer you accepted is correct one. I added in your code some logic, that will give you what you want.

$q = mysqli_query(..., "SHOW TABLES LIKE 'prefix%'");
if($q===FALSE) die(mysqli_error(...));
for($row in mysqli_fetch_array($q)){
    $slice = array_slice($row, 0, 1);
    $tbl = array_shift($slice);
$r = mysqli_query(..., "SELECT MAX(`time`) FROM $tbl HAVING MAX(`time`) <= $expiry_time");
    if ($r) { 
     mysqli_query(..., "DROP TABLE $tbl");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top