PHP script using SQL SELECT query to retrieve records with dates greater than a specified value, including dynamic PHP variables

After reading through various threads on this issue, I still haven't found a solution that incorporates php variables.

I am trying to retrieve the first 100 new records after a specific date from my database, but I'm struggling to make it work.

$connStr =
    'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
    'Dbq='.$ini_project['general']['document_location'].';';

$dbh = new PDO($connStr);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$time = strtotime('6-8-2017 21:52:00');

$date = date('j-n-Y H:i:s',$time);

$sql1  = "SELECT TOP 100 * FROM `$table_name $table_number` WHERE Systeemtijd > `$date`";

$result = $dbh->query($sql1);

while($row = $result->fetch()) {
      print_r($row);
}

I can successfully select records based on another field in the table (WHERE value > 200 for example), but I'm facing issues when attempting to filter based on the date column in the table. I have also tried without `` and using:

$sql1  = "SELECT TOP 100 * FROM `$table_name $table_number` WHERE Systeemtijd > DATE `$date`";

However, all attempts result in the same error message:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 0 [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'Systeemtijd > 6-8-2017 21:52:00'. (SQLPrepare[0] at ext\pdo_odbc\odbc_driver.c:206)' in C:\Bitnami\wampstack-5.6.30-1\apache2\htdocs\php7\DataBuilt\Larissa_Connector\data_uploader.php:65 Stack trace: #0 C:\Bitnami\wampstack-5.6.30-1\apache2\htdocs\php7\DataBuilt\Larissa_Connector\data_uploader.php(65): PDO->query('SELECT TOP 100 ...') #1 {main} thrown in C:\Bitnami\wampstack-5.6.30-1\apache2\htdocs\php7\DataBuilt\Larissa_Connector\data_uploader.php on line 65

Answer №1

It's essential to avoid passing variables in a vulnerable manner, always keep in mind how important it is to escape them correctly. Consider using PDO::prepare for safe variable binding:

/* Prepare and execute statement with an array of values */
$sql = "SELECT TOP 100 * FROM $full_table_name
  WHERE Systeemtijd > :date";
$sth = $dbh->prepare($sql);
$sth->execute(array(':date' => $date));
$red = $sth->fetchAll();

Learn more about PDO prepare method here.

Answer №2

When working with Access SQL, it's important to use date formats like #yyyy/mm/dd# or #mm/dd/yyyy#. Using any other format can lead to issues.

$date = date('#y/n/j- H:i:s#',$time);

$sql1  = "SELECT TOP 100 * FROM `$table_name $table_number` WHERE Systeemtijd > $date";

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

Please include the document with a name that contains spaces

I am facing an issue where I cannot attach files with spaces in the name. However, when a file with no space in the name is successfully attached. I am using CodeIgniter for this purpose, uploading the file to the server before attaching it. I use the help ...

Eliminate duplicate time slots in Laravel and Vuejs

Currently, I am delving into laravel(5.2) and vuejs as a newcomer to both frameworks. My goal is to utilize vuejs to eliminate redundant time slots. In my blade file, the code looks like this: <div class="form-group"> <label for="form-fi ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

Executing JavaScript function by clicking on <img>

I've been developing a website similar to YouTube, and I'm facing difficulties with the Like/Dislike feature for comments. Currently, I have implemented it in the following way: when a user clicks on an image (thumbsUp.png or thumbsDown.png), a ...

Obtain the month, day, or year from a timestamp

Can anyone provide guidance on extracting a specific date format (date, month, day, year) from a timestamp? I am interested in implementing this feature within a view using Backbone JS. ...

The functionality of the Vueify modal seems to be malfunctioning when incorporating Vueify alongside a central Modal.vue file that houses modal templates

I've been experimenting with integrating this tutorial on creating reusable modal dialogs with Vuejs and adapting it for use with Vueify. Initially, I was able to successfully implement it, but after exploring a different approach briefly, I returned ...

Is there a way I can obtain the code for a message box?

When I refer to a message box, I am talking about a container that gives users the ability to input their text and access different features like BOLD, ITALIC, color, justify, etc., in order to customize their message's appearance! (Think of it as the ...

What is the best way to calculate the number of days between today's date and the end of the current month using Moment.js?

Here's the current code snippet I am working with: const moment = require('moment') const m = moment const currDay = m().format('D') const dayOfWeek = m().format('dddd') const daysInMonth = m().daysInM ...

How to drop several pins on Google Maps with JavaScript

I am working on incorporating multiple markers into a Google map using ajax, javascript, and php. Although there are no errors in my code, the markers are not appearing as expected. I would greatly appreciate any assistance with this issue. Please refer to ...

Warning displayed on form input still allows submission

How can I prevent users from inserting certain words in a form on my website? Even though my code detects these words and displays a popup message, the form still submits the data once the user acknowledges the message. The strange behavior has me puzzled. ...

When using PHP, JavaScript, and HTML, you can trigger an image upload immediately after choosing a file using the

I currently have a small form with two buttons - one for browsing and another for uploading an image. I feel that having two separate buttons for this purpose is unnecessary. Is there a way to combine the browse and upload functions into just one button? ...

When provided with varied inputs, new Date() yields distinct values for various time zones

var date1 = "2015-03-29"; console.log(new Date(date1)); //Output:Sun Mar 29 2015 05:30:00 GMT+0530 (India Standard Time) var date2 = "1869-12-31"; console.log(new Date(date2)); //Output:Fri Dec 31 1869 05:53:20 GMT+0553 (India Standard ...

JavaScript doesn't automatically redirect after receiving a response

Hey there, I'm attempting to implement a redirect upon receiving a response from an ajax request. However, it seems that the windows.href.location doesn't execute the redirect until the PHP background process finishes processing. Check out my cod ...

Accessing form data from Ajax/Jquery in php using $_POST variables

Thank you in advance for any assistance on this matter. I'm currently attempting to utilize Ajax to call a script and simultaneously post form data. While everything seems to be working correctly, the $POST data appears to come back blank when trying ...

Issue: The plugin 0 mentioned in the file "/my dir/node_modules/babel-preset-php/src/index.js" contains an invalid property called "default"

While attempting to convert a PHP script to JavaScript using babel-preset-php, I encountered the following error: Error: Plugin 0 specified in "/media/deep/5738c180-2397-451b-b0b5-df09b7ad951e1/deepx/Documents/TestingAll/node_modules/babel-preset-php/ ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Storing data with Laravel 5.3 using Storage::put and XMLHttpRequest

Attempting to send a file using DRAG & DROP with XMLHttpRequest. $images = $_FILES['images']; When I use foreach: foreach($images["name"] as $file => $name) and move_uploaded_file($images["tmp_name"][$file], $images_dir . $name it works ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

What steps should I take to generate a stylized date input in javascript?

Looking to dynamically create a date string in JavaScript with the following format: dd-MMM-yyyy Need the dd part to change between 1 and 29 each time I generate the variable within a loop Month (MMM) should be set as Jan ...