Skip to content
Advertisement

Convert string to date datatype in SQL Server in PHP Laravel

I’m trying to get a product by id between a specific date range but the problem I’m facing is:

  1. date is in string format
  2. for some weird reason dates are stored in the database with an incomplete timestamp (eg: ’12-04-2020 12:21′) which I’m trying to get rid of

Using Laravel’s Eloquent below query works without the last line (AND…) which is my attempt to perform date conversion.

I may be able to solve this issue with MySQL but current task is to use SQL Server not really sure what went wrong here any help is much appreciable.

JavaScript

Advertisement

Answer

It seems that you are storing datetime values as text in your table (if it’s possible, try to fix that issue). So, to find a solution to your problem, you may try the following:

  • Convert the values in the column TRANSACTIONS_HD.TRANS_DATE using an appropriate style.
  • Use an unambiguous format (yyyymmdd) for dates in $from and $to variables.
  • Use parameter bindings in your SQL statements to provide protection against SQL injection.

Example (based on your code):

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement