A
A
Alexander2016-07-25 20:22:32
PHP
Alexander, 2016-07-25 20:22:32

How bad is automatic type conversion when writing to the database?

I use PDO (prepared emulation mode is disabled) to work with the database.
Let's take an example:
Let's say we have a string consisting of numbers (string) "0123456789", we need to write it to the database as INT. Is it possible to use a (own) function that automatically casts a variable to one type or another? Or is it still better to use bindValue(':str', $str, PDO::PARAM_INT); ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
trevoga_su, 2016-07-26
@websiteserf

Casting a variable type in PHP for subsequent writing to the database does not make sense. Either you use prepared, or you form the query string with your hands, respectively, the number will also be presented as a string.
Further, on different OS and different platforms PHP_INT_MAX differs. Those. to lead STUPIDLY a line to (int) - absolutely not the correct decision. If you operate on large numbers that go beyond PHP_INT_MAX, then casting to int will simply truncate the number. And numbers beyond PHP_INT_MAX are interpreted by PHP as floating point numbers.
When I wrote my wrapper for mysql , I had a task - to check whether the variable is a number, integer or floating point.
As a result, we got the following code, which covers all tests:
integer definition: https://github.com/Vasiliy-Makogon/PHP-Class-to-sa...
float definition: https://github.com/Vasiliy-Makogon/PHP-Class-to-sa...

M
Mikhail Osher, 2016-07-25
@miraage

If the database field is declared as an integer, integer will be inserted there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question