这成功地从表中检索了数据,但是没有使用mySQL准备好的语句。
$sql = "SELECT email, created_at, firstname, lastname FROM users WHERE id ='" . $_SESSION['id'] . "'";
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$email_address = $row["email"];
$creatiom_time = $row["created_at"];
$fname = $row["firstname"];
$lname = $row["lastname"];
}
}
如何将其转换为准备好的语句以防止SQL注入?我尝试转换它不会检索数据。
$stmt = mysqli_prepare($link, "SELECT email, created_at, firstname, lastname FROM users WHERE id=?");
$stmt->bind_param("i", $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($email_address, $creatiom_time, $fname, $lname);
$stmt->close();
我在做什么错?电子邮件是唯一的,因此它应该只返回一行;但是,当我使用上述准备好的语句时,什么也不会返回。谢谢。
答案 0 :(得分:4)
您实际上需要使用fetch
将行数据存储到绑定的结果变量中:
$stmt = mysqli_prepare($link, "SELECT email, created_at, firstname, lastname FROM users WHERE id=?");
$stmt->bind_param("i", $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($email_address, $creatiom_time, $fname, $lname);
$stmt->fetch();
$stmt->close();
echo $email_address; // etc.
请注意,您确实应该检查这些调用的返回状态,尤其是prepare
,execute
和fetch
。