Search code examples
phpmysqlmysqliprepared-statementbindparam

php-use "s" or "i" for long in bind_param()?


in regard to bind_param() function of a prepared statement, it is mentioned in the php documentations that:

If you specify type "i" (integer), the maximum value it allows you to have is 2^32-1 or 2147483647. So, if you are using UNSIGNED INTEGER or BIGINT in your database, then you are better off using "s" (string) for this.

here it is saying we should use s for big int columns. but I tried i to insert a long in a big int column and it worked fine. so it confuses me! for big int should we actually use s or i?!


Solution

  • You should almost always use s for everything. There are only a handful of scenarios when you would like mysqli to cast the value to the appropriate type for you. Binding everything as a string is the safest option. SQL will cast the value anyway to the type that it needs.

    The comment you have found on php.net website meant that if you cast an integer string to a PHP native integer then it might overflow on 32-bit systems. PHP uses signed integers which means that the max value on a 32-bit system is only 2147483647. If you have an integer larger than this, you should use strings to prevent overflow.

    Both, BIGINT (64-bit integer) and signed INT, are larger than the maximum integer on a PHP 32-bit system. However, if bind everything as a string you don't need to worry about losing any value.