問題描述
我在 MySQLi 中使用 PHP,我遇到了類似查詢的情況
I'm using PHP with MySQLi, and I'm in a situation where I have queries like
SELECT $fields FROM $table WHERE $this=$that AND $this2=$that2
到目前為止,我已經(jīng)編寫了一些代碼來拼接我給它的數(shù)組,例如:
So far I've written some code that splices up an array that I give it, for example:
$search = array(name=michael, age=20) //turns into
SELECT $fields FROM $table WHERE name=michael AND age=20
有沒有更有效的方法來做到這一點?
Is there a more efficient way to do this?
我很擔心 MySQL 注入 - 這似乎很容易受到攻擊.謝謝!
I'm rather worried about MySQL injections - this seems very vulnerable. Thanks!
推薦答案
奇怪的是,問題的標題基本上就是它的答案.你想要做這樣的事情,使用 mysqli 參數(shù)化查詢:
Oddly enough, the title to your question is basically the answer to it. You want to do something like this, using mysqli parameterized queries:
$db = new mysqli(<database connection info here>);
$name = "michael";
$age = 20;
$stmt = $db->prepare("SELECT $fields FROm $table WHERE name = ? AND age = ?");
$stmt->bind_param("si", $name, $age);
$stmt->execute();
$stmt->close();
更多信息在mysqli部分,特別是相關(guān)的功能MySQLi_STMT.
More information in the mysqli section of the manual, specifically the functions related to MySQLi_STMT.
請注意,我個人更喜歡使用 PDO 而不是 mysqli,我不就像 mysqli 所做的所有 bind_param
/bind_result
東西一樣.如果我必須使用它,我會圍繞它編寫一個包裝器,使其更像 PDO.
Note that I personally prefer using PDO over mysqli, I don't like all the bind_param
/ bind_result
stuff that mysqli does. If I have to use it I write a wrapper around it to make it work more like PDO.
這篇關(guān)于MySQLi 中的參數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!