Mysqli支持准备好的语句,可防止SQL注入攻击。它看起来是这样的:
/* Create a prepared statement */
$stmt = $mysqli -> prepare("SELECT column FROM table WHERE name=?");
/* Bind parameters */
$stmt -> bind_param("s", $_POST['checkname']);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
echo $result;
查看manual了解更多信息。
的简要介绍,以响应注释:
在$stmt->prepare("...")
,你形成你的查询,你持有任何变量你打算用用“的地方?”
在$stmt -> bind_param(...)
中,您将变量绑定到相应的问号。第一个参数是类型,下面的参数是变量。如果您使用的是字符串和整数,在括号内部,它看起来就像"si", $stringVar, $intVar
在$stmt -> bind_result(...)
您说明您要绑定的结果。如果查询是针对某个名称和年龄的,那么该内容看起来就像$name, age
在$stmt->fetch()
中,您正在获取结果。如果是多行回来,你会做这样的事情:
而($ stmt->取()){// 代码在这里 }
或者,你可以使用PDO。它看起来像这样:
/* Create a prepared statement */
$stmt = $pdo->prepare("SELECT column FROM table WHERE name=:checkname");
/* Bind parameters */
$stmt->bindParam(':checkname', $_POST['checkname']);
/* Execute it */
$stmt->execute();
/* Fetch results */
$obj = $stmt->fetchObject();
echo $obj->column;
查看manual了解更多信息。
[Escaping](http://www.php.net/manual/en/mysqli.real-escape-string.php)将有助于正确地做到这一点。更好的是Mysqli已经支持的[bound params](http://www.pontikis.net/blog/dynamically-bind_param-array-mysqli)。 – mario