Dates & Datetimes when reading from MSSQL in PHP
So it gets me every time I try to deal with dates in a query result when I’m getting rows from a MSSQL database in PHP. Normally I work with MySQL when I’m programming in PHP, but I have a hybrid application where .Net is used on the front end, and I do a bunch of back end things using PHP scripts. So here’s the issue. MSSQL doesn’t store things the same way MySQL does. MySQL seems to treat everything like a string. Combine that with PHP’s ability to treat basically anything like a string, and you’ve got a good pair where you can get away without type casting. MSSQL actually type casts some things it stores for you. When you look at Date Times for instance, you’ll see they’re stored as an object. Here’s a dump of the structure.
[time_created] => DateTime Object
[date] => 2013-03-27 16:34:41
[timezone_type] => 3
[timezone] => America/New_York
Now if you view this in Microsoft SQL Server management studio, you’ll only see the date portion, which is why I never remember that it’s an object. So, if you select it in PHP as a $row, to get the actual date in the string format PHP programmers would be used to, you’d have to do the call below. Assume that the field name is time_created.
Now notice that we use the -> format because it’s an object, not a 2 dimensional array. The $row is an array because it’s the results of a query.