MySQLi 中的参数

2021-12-25 00:00:00 parameters php mysqli

我在 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

到目前为止,我已经编写了一些代码来拼接我给它的数组,例如:

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 参数化查询:

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部分,特别是相关的功能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.

相关文章