简体   繁体   English

MySQLi中的参数

[英]parameters in MySQLi

I'm using PHP with MySQLi, and I'm in a situation where I have queries like 我正在使用PHP和MySQLi,而我遇到的问题就像是

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? 有没有更有效的方法来做到这一点?

I'm rather worried about MySQL injections - this seems very vulnerable. 我更担心MySQL注入 - 这似乎非常脆弱。 Thanks! 谢谢!

Oddly enough, the title to your question is basically the answer to it. 奇怪的是,你问题的标题基本上就是答案。 You want to do something like this, using mysqli parameterized queries: 你想做这样的事情,使用mysqli参数化查询:

$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();

More information in the mysqli section of the manual , specifically the functions related to MySQLi_STMT . 有关MySQLi_STMT的相关函数,请参阅 本手册mysqli部分中的更多信息。

Note that I personally prefer using PDO over mysqli, I don't like all the bind_param / bind_result stuff that mysqli does. 请注意,我个人更喜欢使用PDO而不是mysqli,我不喜欢mysqli所做的所有bind_param / bind_result If I have to use it I write a wrapper around it to make it work more like PDO. 如果我必须使用它,我会在它周围编写一个包装器,使其更像PDO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM