Home  >  Article  >  Backend Development  >  Pay attention to the range of numbers when formatting numbers in php_PHP Tutorial

Pay attention to the range of numbers when formatting numbers in php_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:39:28905browse

Constructing a sql statement is compared to

Copy code The code is as follows:

$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:
Copy code The code is as follows:

$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 quite simple. If it is more complicated, if you use string concatenation, it is simply a Nightmare.

It is more convenient to use the second method. But there is a small problem: when formatting numbers, you need to pay attention to their value range. The numerical operation is used to obtain the value and the question is asked. Then the sql returned in the end is not what we need.

I made a summary today:

%d: 2^31~2^31-1(-2147483648~2147483647) (convert int to signed decimal)

%b: Binary (convert int type to binary)

%c: Character (convert int type to character)

%u: 2^32-1(0 ~ 4294967295) (Convert int to signed decimal)

%f: -2^128-2^128(-3.4E38 ~+3.4E38) (Convert float to float) Localization

%F: -2^128-2^128(-3.4E38 ~+3.4E38) (convert float to float) non-localization

%o (convert int to octal)

%s: String

%x: Convert int to hexadecimal of lowercase letters

%X: Convert int to hexadecimal of uppercase letters

Because the id in the database may be very large, if %d is used, it may be out of range and the correct result may not be obtained. Therefore, I personally recommend that when formatting IDs, it is much better to use %.0f than %d.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321541.htmlTechArticleConstructing the sql statement is as follows: $sql = 'SELECT * FROM sdb_comments WHERE goods_id = '. intval($goods_id).' AND for_comment_id IS NULL AND object_type = ".$ite...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn