ODBC connection returns only strings as data type

2019-09-03 12:25发布

问题:

I'm currently working with PHP and MS Access. I have a simple table with different data types. The connection to the database works good but, if I do a var_dump to the query, I notice that all data type are all converted to strings. If I use the same database with ASP I got the data types correct. The problem seems to be only with PHP and the ODBC driver.
Is there any way to get those values with their correct data type?
Any help would be greatly appreciated.

回答1:

While it is true that an Access ODBC connection in PHP returns all fields as string, e.g.

array(5) {
  ["ID"]=>
  string(1) "1"
  ["TextField"]=>
  string(13) "This is text."
  ["IntegerField"]=>
  string(1) "3"
  ["DateTimeField"]=>
  string(19) "2014-03-01 00:00:00"
  ["CurrencyField"]=>
  string(8) "100.0000"
}

it really doesn't matter because PHP will just cast the strings to numbers when you use them in a calculation. (Or, you can explicitly cast them as explained here.)

The only fields that require special handling are the Date/Time fields, and then all you need to do is pass them to strtotime() and they will be converted to Unix timestamp values:

$data = odbc_fetch_array($result);
$datetime = strtotime($data["DateTimeField"]);
echo '$datetime value is: ' . $datetime;
echo "\r\n\r\n";
echo '$datetime formatted with date("c", ...) is: ' . date("c", $datetime);

results in

$datetime value is: 1393650000

$datetime formatted with date("c", ...) is: 2014-03-01T00:00:00-05:00