Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

purpose of the max number in php & mysql

Tags:

php

mysql

What is the main purpose for the maximum limit for number in php and mysql?
Does this means that we can/cannot process or store numbers that is larger than the limit?

I echo PHP_INT_MAX and it shows 2147483647.

I multiply by 1000000000000000000000 and get answers like 2.147483647E+30 which i think is already over the limit?

Please advise.

Many thanks for guidance.

This question arise when I'm thinking about validating the user form input. I want to make sure that the user input is according to our defined number format and not something else.
Then i do some online search for best practices and come to aware of this "limits" but do not know how to handle it correctly when using PHP & MYSQL. Pls advise:

Step 1: trim and convert user form input "string number" to number.
Step 2: validate the number is in positive integer format.
Step 3: validate the number does not exceed my "max limit".
Since php limit (2,147,483,647) is smaller than mysql limit (18,446,744,073,709,500,000)? i'll take php as my max limit.
Step 4: perform some calculations...
Step 5: validate my result does not exceed my max limit.
Step 6: store the result in mysql.

like image 253
user1884324 Avatar asked Oct 03 '22 20:10

user1884324


2 Answers

It's hardware limit of the CPU. You can still use bc math function to work with larger numbers. In mysql it is about aligning bytes, so it knows at which offset is which column.

The multiply result is converted to float.

like image 120
Marek Avatar answered Oct 07 '22 19:10

Marek


PHP_INT_MAX is the constant of the largest integer you can use on this build of PHP (32 bit in your case). If your OS and CPU support 64 bit, you can use a 64 bit build of PHP to support a much larger number in an integer. (This causes problems where developers have designed their code around the limits of a 64 bit build and is then used on 32 bit builds, assuming the type matters.)

When you multiply the number by a larger one, PHP recognises this new value is not going to fit in an integer and converts the type to a long or float. In the latter case, you would lose some precision, so it's important you're careful when considering how your code affects variable types. In some languages, you would receive an error for trying to set a value larger than was allowed by that type, because the language would refuse to change the type automatically for you. In this way, PHP is a more basic programming language to use.

<?php
$my_number = PHP_INT_MAX;
var_dump(gettype($my_number), $my_number);
$my_number = $my_number * 1000000000000000000000;
var_dump(gettype($my_number), $my_number);

Output:
string(7) "integer"
int(2147483647)
string(6) "double"
float(2.147483647E+30)
like image 45
deed02392 Avatar answered Oct 07 '22 18:10

deed02392