When formatting Numbers in PHP pay attention to the range of Numbers
- 2020-03-31 20:37:16
- OfStack
Constructing SQL statements is compared to
I prefer to do this:
This statement is relatively simple, if it is more complex, using concatenated strings, it is a nightmare.
The second method is more convenient, but there is a small problem: when formatting a number, you need to pay attention to its value range. The number operates on the value of the inverse question. Then the final return SQL is not what we need.
I made a summary today:
%d: 2^31~2^31-1(-2147483648~2147483647) (converts int to signed decimal)
%b: binary (converts int to binary)
%c: character (converts an int to a character)
%u: 2^32-1(0 ~ 4294967295) (converts int to signed decimal)
%f: -2^128-2^128(-3.4e38 ~+3.4E38)(converts float to float) localization
%F: -2^128-2^128(-3.4e38 ~+3.4E38)(converts float to float) unlocalized
%o (converts int to octal)
% s: string
%x: converts int to hexadecimal in lower case
%X: converts int to hexadecimal in uppercase
Because the ids in the database can be very large and if you use %d, you can get out of range and not get the right result. So, I personally recommend using %.0f rather than %d for id formatting.
$sql = 'SELECT *
FROM sdb_comments
WHERE goods_id = '.intval($goods_id).'
AND for_comment_id IS NULL
AND object_type = ".$item."
AND disabled="false"
AND display = "true"';
I prefer to do this:
$sql = sprintf('SELECT *
FROM sdb_comments
WHERE goods_id = %.0f
AND for_comment_id IS NULL
AND object_type = "%s"
AND disabled="false"
AND display = "true"', (float)$goods_id, $item);
This statement is relatively simple, if it is more complex, using concatenated strings, it is a nightmare.
The second method is more convenient, but there is a small problem: when formatting a number, you need to pay attention to its value range. The number operates on the value of the inverse question. Then the final return SQL is not what we need.
I made a summary today:
%d: 2^31~2^31-1(-2147483648~2147483647) (converts int to signed decimal)
%b: binary (converts int to binary)
%c: character (converts an int to a character)
%u: 2^32-1(0 ~ 4294967295) (converts int to signed decimal)
%f: -2^128-2^128(-3.4e38 ~+3.4E38)(converts float to float) localization
%F: -2^128-2^128(-3.4e38 ~+3.4E38)(converts float to float) unlocalized
%o (converts int to octal)
% s: string
%x: converts int to hexadecimal in lower case
%X: converts int to hexadecimal in uppercase
Because the ids in the database can be very large and if you use %d, you can get out of range and not get the right result. So, I personally recommend using %.0f rather than %d for id formatting.