views:

34

answers:

1

Running php 5.2.5 on Windows Server 2003 (64 bit) and connecting to SQL Server 2008

Having issues getting datetime fields from SQL Server using mssql_query. Any datetime field that I query returns nothing. All other fields in the query are correct, but the datetime fields are blank.

We switched from PEAR DB to mssql_ functions recently and that was the cause of the issue. Switching back to PEAR is not an option.

I found this on php.net mssql_query page and it does work, but I've got hundreds of queries and I was hoping there was a solution that wouldn't require us updating every single query. Anyone have a better solution that would not involve rewriting every query?

"I was tripped up by the fact that mssql_query() returns values for 'datetime' columns in an unusual format. In order to get your values returned in the usual 'YYYY-MM-DD HH:MM:SS' format, you can use the CONVERT function in your query like so:

SELECT CONVERT(varchar, INVOICE_DATE, 121) AS INVOICE_DATE ...

where 'INVOICE_DATE' is the name of the 'datetime' column."

A: 

Ended up just doing some string replacement to work around this.

First I created an array of date fields that I could possibly select from the SQL Server DB I was working with.

We've got a DB Abstraction class we run every query through.

In the DB class I check to see if "FROM" was in the query. If it was I split the string on FROM to get the SELECT fields part Then I do a foreach on the array of fields and if that field exists in the string I replace the field with CONVERT(varchar, FIELD, 121) AS FIELD

Works great for me...doesn't work with SELECT * but we don't use any SELECT * queries so not a problem for us.

Jason