PHP PDO Remove records older than user-specified number of days

Recently, I delved into the world of PHP and database management about a month ago. Luckily, most of my issues were resolved through diligent Google searches.

Currently, I am working on creating an admin feature that allows for the deletion of entries older than a specified number of days. However, I suspect there may be an issue with my PDO syntax, particularly with the part involving ':days'.

Here is the snippet of PHP code:

$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)");
    $statement->execute(array(':days' => $days));
}

And here's the corresponding HTML form:

<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>

An error message is being displayed:

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

Answer №1

DAY must be used in the singular form.

DATE_SUB(NOW(), INTERVAL :days DAY)

Answer №2

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

Your SQL statement had an incorrect spelling mistake.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Uploading multiple files using PHP on an Ubuntu server

I have encountered an issue while attempting to upload multiple files in tsv and csv formats using PHP. The following HTML and PHP script has been included below. It successfully uploads files when executed with XAMPP on a Windows system. However, when I a ...

What is the standard way to write the server-side code for HTTP request and response handling?

I stumbled upon these resources: How to send HTTP request GET/POST in Java and How to SEND HTTP request in JAVA While I understand the client-side aspect, how can this implementation be done on the server side? The goal is to utilize the link on the clie ...

What could be causing my search function to not recognize special characters?

It seems like there might be an issue with character encoding. My JavaScript search function is unable to identify specific strings that contain certain special characters such as parentheses, asterisks, and numbers. The JavaScript code I am using is quit ...

jade, express, as well as findings from mysql

My goal is to display the results of an SQL query in Jade, which pulls data from a table of banners. Each banner has a unique id and falls under one of three types. Here is my current code : express : connection.query("SELECT * FROM banner_idx ORDER BY ...

Using the window.history.pushState function triggers a page reload every time it is activated

I've been attempting to navigate from page to page without the need for a reload. I came across suggestions that using window.history.pushState() could achieve this, however, it appears that the page is still reloading. Furthermore, an attempt ...

Counting the days: how to calculate without using negative numbers

After performing the calculation, the result shows -30. Is there a way to eliminate the negative sign and get 30 instead? $days = (strtotime(date("Y-m-d")) - strtotime($info['expiredate'])) / (60 * 60 * 24) echo abs($days); Any suggestions on ...

Retrieving all rows from MySQL using PHP when a variable is empty

$frame_type = ''; $ret = mysqli_query($con, "select * from products where status='1' AND frame_type = '$frame_type' "); while ($row = mysqli_fetch_array($ret)) { $emparray[] = $row; } Retrieve All ...

Fetching data from multiple tables in CodeIgniter using PHP and jQuery and returning it asynchronously with Ajax

Currently, I am utilizing jQuery to retrieve JSON data through AJAX from a CodeIgniter backend and MySQL database, which is functioning correctly. However, the issue I am facing is that in addition to fetching the data returned to the jQuery function, I al ...

Vertical scrollbar in iframe unexpectedly appears immediately after the submit button is pressed

I have designed a contact form that is displayed in an iframe within an overlay div. I have carefully adjusted the dimensions of this div to ensure that there are no scrollbars visible when the form initially appears. However, after filling out the form an ...

php for the upcoming week and the following week

I have successfully retrieved the date of the Monday for the current week, but I am unsure how to display it along with the date for the following week's Monday in a sentence. Can someone assist me with this issue? For instance, I would like the outp ...

Unable to retrieve data from CKEditor using Ajax

Having some issues with my AJAX implementation in PHP, specifically trying to retrieve data from CKEditor but encountering difficulties. Here are my codes: <form> <textarea id="editor" name="Content" required></textarea&g ...

Transform an array containing objects into a single object

Currently exploring the Mapael Jquery plugin, which requires an object to draw map elements. In my PHP code, I am returning a JSON-encoded array of objects: [ { "Aveiro": { "latitude": 40.6443, "longitude": -8.6455, ...

From JSON Objects to PHP Mistakes

I created a PHP script to display an entire layout of divs with the necessary content. However, upon execution, the result is just a blank page. What could be the issue? Code: <? $url = 'http://socialclub.rockstargames.com/crewapi/the_greeks_360/ ...

Performing calculations on PHP and MySQL data within an HTML table, enabling precise percentage

Here's the code I'm currently working with: <td> <?php echo $row['feild1'] + $row['feild2'] + $row['feild3'] + $row['feild4'] + $row['feild5'] + $row['feild6'] + $row[' ...

Regular expression to validate a word containing at least one letter

Need a regular expression to validate words with at least one letter Here are some examples: spoon (valid) chef87 (valid) 123 (invalid) Yum (valid) 65b(valid) ...

"Utilize the power of the ajaxform jQuery plugin to automatically reset form fields

Initially, I'd like to emphasize that this is an original inquiry. My predicament is as follows: I have a chatroom php script where I utilize the ajaxForm jQuery plugin to seamlessly send new messages without having to reload the entire page. Howev ...

Utilize the HTML Tidy executable in combination with PHP, as opposed to compiling it

I have created a PHP application specifically for shared hosting environments. Dealing with the inconsistency of hosts providing HTML Tidy can be challenging for me. Is there a way to integrate the tidy executable directly into my PHP application and proce ...

PHP Elasticsearch Clustering for Optimized Data Searching

I currently have a PHP application that relies on ElasticSearch for search and insert operations. To improve the speed of my application, I recently implemented clustering in ElasticSearch with a total of 3 nodes (including data nodes). The initial node ...

How can I fetch variables from a mySQL table to utilize them in a different row within the same table?

My lack of experience in SQL/mySQL has led me here with a somewhat basic question. After unsuccessful attempts at finding answers on Google, I present to you the mySQL table that is causing me confusion. create table Contribution ( ContributionID ...

PHP response is blank when password_hash or password_verify functions are used

My application utilizes JavaScript to retrieve a string and send it via POST to a PHP file on the server for processing. The PHP receiver is responsible for parsing the string, performing tasks, and sending back status updates to JavaScript. However, after ...