简体   繁体   中英

PHP PDO Delete older entries than 'x' (user defined) days

First of all, I started with PHP and databases like 1 month ago, but so far I found solutions to most of by problems googling.

I'm trying to make an admin function where you can delete entries older than 'X' days. But I'm pretty sure there is something wrong with my PDO (the :day part).

PHP:

$backsite = $_SERVER['PHP_SELF'];
if (isset($_POST['days'])) {
    $days = $_POST['days'];
    $statement = $db->prepare("DELETE FROM $tbl_name WHERE date < DATE_SUB(NOW(), INTERVAL :days DAYS)");
    $statement->execute(array(':days' => $days));
}

HTML:

<form method="post" action="' . $backsite .'">
    <input type="number" min="7" max="90" placeholder="7" required="" name="days"/>
    <input type="submit" name="delete" value="Delete" />
</form>

Error message:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DAYS)' at line 1' in /Applications/XAMPP/xamppfiles/htdocs/skiss/archive.php:10 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/skiss/archive.php(10): PDOStatement->execute(Array) #1 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/skiss/archive.php on line 10

DAYS必须是单数。

DATE_SUB(NOW(), INTERVAL :days DAY)
$backsite = $_SERVER['PHP_SELF'];
if (isset($_POST['days'])) {
    $days = $_POST['days'];
   $statement = $db->prepare("[DELETE FROM $tbl_name WHERE date < DATE_SUB(NOW(), INTERVAL :days DAY)](dev.mysql.com/doc/en/date-and-time-functions.html)");
   $statement->execute(array(':days' => $days));
}

You had an extra "S" in your SQL statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM