5

PDO MS SQL Server and PDO MySQL both return an array of strings when you fetch, even if the SQL type of the columns were meant to be numeric types such as int or float. I was managed to work around it, but I want to understand why they were designed this way to begin with. Is it because PDO itself don't support it (or didn't support it before)?

1
  • The type of the column doesn't matter, it just defines what can be stored in it, not the type of what's being returned when you fetch something from it. By default, everything returned by PDO is a string, PHP does type-juggling though, so $var = 10; and $var = "10"; (an integer and a string, both assigned to 10) are both treated as numbers. Commented Jul 11, 2016 at 20:51

2 Answers 2

3

With PDO MySQL the underlying C API returns a structure of strings when calling mysql_fetch_row(). Since PHP is a loosely typed language that automatically casts to integer as necessary, I suspect the PDO developers chose to return them as-is. This would be faster than looking up each column type and dynamically casting to an integer / float.

Specifically regarding float, a native PHP float may be different than the original stored value when converted from a string. For example, MySQL columns support a precision while PHP floats do not. Leaving floats as a string from the database allows you more control (e.g. choosing to use a library with different precision).

Sign up to request clarification or add additional context in comments.

1 Comment

there is also a prepared statement
0

because PDO itself don't support it (or didn't support it before)?

Pretty much yes but for mydsql it is not because PDO but because mysql C API.

Since it changed, for the moment PDO can return correct datatypes if you run a native prepared statement against a mysqlnd-based PDO instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.