简体   繁体   中英

PHP Input MS SQL Failed to convert date and/or time from character string

I'm running a MSSQL function and returning to PHP and I'm using the function twice in the PHP and writing it away to a MySQL database.

The first time I run the function I'm using $to and $from (I'm well aware it's not pretty, I'm not a php coder by trade...)

$to = date("j M Y", mktime());
$year = date("Y", mktime());
$jan = '1 jan ';
$from = $jan . $year;

I'm then using the following

select * from MISYearToDate('$from', '$to')

and that works absolutely fine.

When I then do the same thing but putting in this week's dates using

$weekstarting = date('j M Y', strtotime('last sunday'))."<br>";
$weekending = date('j M Y', strtotime('next saturday'))."<br>";

and then run

select * from MISYearToDate('$weekstarting', '$weekending')

I'm getting the error

[Microsoft][SQL Server Native Client 11.0][SQL Server]Conversion failed when converting date and/or time from character string. ) 

$From and $to echo

1 jan 2012
27 Jun 2012

$weekstarting and $weekending echo

24 Jun 2012
30 Jun 2012

So as far as I can tell, there really isn't a difference and I'm pretty damn confused!

I'd recommend only feeding dates into SQL in the format of yyyy-mm-dd. This will ensure SQL doesn't get confused with the date format.

SQL will not accept dates in the format of 1 jan 2012 (as a string).

$weekending = date('j M Y', strtotime('next saturday'))."<br>";
                                                       ^^^^^^^

<br> is not a valid component of an SQL date string. You're probably viewing the output in a browser, so the <br> is effectively hidden, but that's where your problem is.

That's turning your query into:

select * from MISYearToDate('24 Jun 2012<br>', '30 Jun 2012<br>')

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