gpt4 book ai didi

php - 准备好的语句和 mysqli_query/mysqli_num_rows?

转载 作者:行者123 更新时间:2023-12-02 17:31:48 25 4
gpt4 key购买 nike

我正在尝试找出如何使我的代码与准备好的语句一起工作。我理解整个过程,直到我评论我的代码。我需要做什么才能正确集成 num_rows 和 mysqli_query 部分?

function login_check() {

global $connection;

$name = $_POST['name'];
$password = $_POST['password'];

$query = "SELECT id FROM members WHERE name = $name AND password = $password";
$stmt = $connection->prepare($query);
$stmt->bind_param('ss', $name, $password);
$stmt->execute();
$stmt->close();

// $result = mysqli_query($connection, $query);
// $rows = mysqli_num_rows($result);

if($rows > 0){
header('location:../../success.php');
exit;
}

else {
header('location:../../failed.php');
exit;
}
}

我尝试了什么:

$result = mysqli_query($connection, $stmt);
$rows = mysqli_num_rows($result);

最佳答案

改变

$query = "SELECT id FROM members WHERE name = $name AND password = $password";

$query = "SELECT `id` FROM `members` WHERE `name` = ? AND `password` = ?";

在表和列周围添加反引号可以防止 mysql 保留字错误。

删除$stmt->close();

if( $stmt->num_rows > 0 ) {
$stmt->close();
header('location:../../success.php');
exit();
} else {
$stmt->close();
header('location:../../failed.php');
exit();
}

在这种情况下,在 header 之前的 if 语句中添加 $stmt->close() 是最佳实践。因为在 if 语句之前添加它会导致 $stmt->num_rows 总是返回 0;在 if 语句之后添加它是行不通的,因为 exit() 会阻止它执行。

来自documentation :

Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

关于php - 准备好的语句和 mysqli_query/mysqli_num_rows?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32200341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com