问题描述
我正在尝试检查数据库中是否已存在输入值.
I am trying to check if an input value already exists in my database.
到目前为止,我得到了以下内容,但这始终使我返回无效"(即使我输入了匹配的值),所以我的猜测是我的SELECT查询后的部分或If Else逻辑中存在错误.
So far I got the following but this always returns me "Invalid" (even if I enter a matching value) so my guess is I have an error in the part after my SELECT query or in my If Else logic.
有人可以告诉我该怎么做吗?
Can someone tell me how to do this right?
我的JS:
$('#btnCheck').click(function() {
var username = $('#username').val();
$.ajax({
url: 'userSubmit.php',
type: 'POST',
data: {username: username},
success: function(response){
if(response == 'valid') {
alert('Valid');
} else {
alert('Invalid');
}
}
});
});
我的PHP:
$username = $_POST['username'];
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
die("Connection Error: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT username FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
if($stmt->num_rows > 0) {
echo "valid";
} else {
echo "invalid";
}
推荐答案
在调用num_rows
之前,您需要调用store_result()
以便实际记录行数:
You need to call store_result()
in order for the number of rows to actually be recorded before calling num_rows
:
...
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0) {
...
必须调用store_result()
的原因是,如果没有此调用,则实际上不会获取任何结果,因此行数(num_rows
)将是0
.
The reason why you must call store_result()
is that without this, no results have actually been fetched, and the number of rows (num_rows
) will therefore be 0
.
参考num_rows
的官方文档:
与此相关的链接是此处.
这篇关于使用PHP/MySQLi查询的Ajax调用返回错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!