使用PHP/MySQLi查询的Ajax调用返回错误结果 [英] Ajax call with PHP / MySQLi query returning wrong results

查看:72
本文介绍了使用PHP/MySQLi查询的Ajax调用返回错误结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查数据库中是否已存在输入值.

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的官方文档:

返回结果集中的行数.指某东西的用途 mysqli_stmt_num_rows()取决于您是否使用过 mysqli_stmt_store_result()将整个结果集缓存在 语句句柄.

Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.

与此相关的链接是此处.

这篇关于使用PHP/MySQLi查询的Ajax调用返回错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆