2

I'm trying to connect from PHP to a ms access database and, with help from here, so far so good!

But all data retrieved is "String" type, even date/time and numeric fields are converted to string in php. And some numeric values only show a string with "E2".

Here is my code:

$dbName = "database.accdb";
$conn2 = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=$dbName;Uid=Admin");
$conn2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn2->prepare("SELECT * FROM table");
$stmt->execute();
$result= $stmt->fetchAll();

There are numeric fields, string fields, and date/time fields in that table, but the array $result has data type "String" in all elements. Used gettype() to check.

The problem is that numeric values get converted sometimes to "0.0353125" (for example) or only "E-3" or "E-2"

How can I get the correct value in my $result array? What am I doing wrong?

Thanks a lot

acuraitu
  • 21
  • 1
  • Unfortunately, all database types are not included in php system types (array, string, int, float, bool). There is also in database dates, geometry, ... So to be compliant, pdo automatically retrieves values as string. You might use `is_float(mixed $var)` to check if you variable is a float. – Anwar Sep 16 '16 at 10:57
  • I'm pretty new to this, so let me check if I understood: is_float() is a php function, so will always return false because all element of my array are already string. I understand that with pdo and microsoft acces the $result will always have STRING values? Thanks a lot, will try to use them as strings and convert. THANKS! – acuraitu Sep 16 '16 at 11:08
  • `is_float()` actually try to transform everything (including a string) into a float number. If it succeed, it returns true. So if you do `is_float('test');` it returns false, but if you do `is_float('1.896e-5');` it returns true because this string can be "parsed" into a float. – Anwar Sep 16 '16 at 12:12
  • Nice! Will try this weekend, and I'll keep you updated! – acuraitu Sep 16 '16 at 12:58
  • It looks like PDO_ODBC may suffer from the same limitation as pypyodbc when working with the Access ODBC driver and float values as described [here](http://stackoverflow.com/a/33900787/2144390). – Gord Thompson Sep 16 '16 at 14:10
  • @GordThompson -you didn't reference your more pertinent [PHP ODBC answer](http://stackoverflow.com/questions/22157340/odbc-connection-returns-only-strings-as-data-type). – Parfait Sep 18 '16 at 01:15
  • @Parfait - Thanks for the reminder. I was focusing on the "E-3" weirdness, which seems to be more a function of the ODBC middleware implementation than the driver itself. – Gord Thompson Sep 18 '16 at 01:56

0 Answers0