所以都沒有sql query的特殊字元問題
但有時,純用php做sql query
一直在想有什麼比較好的寫法 去過濾sql query的特殊字元問題
不是用addslashes(),就是用mysql_real_escape_string()完成
不過程式碼就變超長的
如果參數多 就不容易看出來在寫啥
$query = "SELECT * FROM users WHERE
user = '" . mysql_real_escape_string($user) ."'
AND '" . mysql_real_escape_string($password) ."'";
看完php api用sprintf的寫法 覺得早該這樣寫了...
雖然還是很長..... 不過感覺比較有結構了
以前寫C#就有了,不過換個語言也換個腦袋了... 居然都沒想到...
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'"
,mysql_real_escape_string($user)
,mysql_real_escape_string($password));
附上常用的參數
- % - a literal percent character. No argument is required.
- d - the argument is treated as an integer, and presented as a (signed) decimal number.
- f - the argument is treated as a float, and presented as a floating-point number (locale aware).
- F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3.
- s - the argument is treated as and presented as a string.
Reference
mysql_real_escape_string
sprintf
addslashes() vs mysql_escape_string()