参数化查询

Fra*_*oko 2 php mysqli

请问这段代码安全吗?

/* Create a new mysqli object with database connection parameters */
$mysqli = new mysql('localhost', 'username', 'password', 'db');

if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}

/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
AND password=?")) {

/* Bind parameters
s - string, b - boolean, i - int, etc */
$stmt -> bind_param("ss", $user, $pass);

/* Execute it */
$stmt -> execute();

/* Bind results */
$stmt -> bind_results($result);

/* Fetch the value */
$stmt -> fetch();

echo $user . "'s level of priviledges is " . $result;

/* Close statement */
$stmt -> close();
}

/* Close connection */
$mysqli -> close();
Run Code Online (Sandbox Code Playgroud)

Pek*_*ica 8

至于防止mySQL注入的问题:是的.Mysqli的参数化查询可以安全地抵御注入攻击.

如果$user来自外部源,您可能需要添加htmlentities()echo语句以防止用户注册用户名等<script>(some malicious code)</script>