問題描述
我已經(jīng)完成了我的研究并決定在我的查詢中使用準(zhǔn)備好的語句,我只問是否有什么我應(yīng)該知道的,關(guān)于切換到普通 mysqli 查詢到準(zhǔn)備好的語句的好壞.
I have done my research and have decided to use prepared statements in my queries, all I ask if there is anything I should know, good or bad about switching to normal mysqli queries to prepared statements.
我也不明白為什么不需要轉(zhuǎn)義壞字符的邏輯?
Also I don't understand the logic how the need for escaping bad characters is not needed?
推薦答案
仍然需要轉(zhuǎn)義壞字符,但庫會自動為您綁定的所有參數(shù)執(zhí)行此操作.它只是稍微方便一些,并且可以防止程序員忘記清理值.
Escaping bad characters is still needed, but the library does it automatically for all parameters you bind. It's just slightly more convenient, and prevents the programmer from forgetting to sanitize a value.
但是,請注意,這種自動化僅限于參數(shù)!
However, note that this automatism is limited to parameters!
以下查詢是安全的,因為 bind_param()
負(fù)責(zé)轉(zhuǎn)義:
The following query is safe, because bind_param()
takes care of escaping:
$code = $_GET["code"];
$name= $_GET["name"];
$percentage= $_GET["percentage"];
$stmt = $mysqli->prepare("INSERT INTO items VALUES (?, ?, ?)");
$stmt->bind_param('iss', code, $name, $percentage);
$stmt->execute();
以下查詢是不安全的,因為您直接放入查詢中的任何內(nèi)容都不會自動轉(zhuǎn)義:
$tablename = $_GET["prefix"]."_items";
$code = $_GET["code"];
$name= $_GET["name"];
$percentage= $_GET["percentage"];
---- UNSAFE! ----
$stmt = $mysqli->prepare("INSERT INTO `$tablename` VALUES (?, ?, ?)");
$stmt->bind_param('iss', $code, $name, $percentage);
$stmt->execute();
也就是說,無論如何都不應(yīng)該使用本示例中所示的動態(tài)表名.但重點是:小心,即使是參數(shù)化查詢!
that said, one shouldn't be using dynamic table names like shown in this example anyway. But the point stands: Be careful, even with parametrized queries!
我能想到的唯一缺點是您無法再看到用于調(diào)試的最終查詢(因為它僅在服務(wù)器端組裝).
The only downside I can think of is that you can't see the final query any more for debugging (because it gets assembled only on server side).
這篇關(guān)于與普通 mysqli 語句相比,使用準(zhǔn)備好的語句的優(yōu)勢是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!