gpt4 book ai didi

php - 使用 Ajax 和 PHP 检查数据库中的现有用户

转载 作者:行者123 更新时间:2023-12-01 04:45:44 25 4
gpt4 key购买 nike

我遇到了一个问题,代码不断显示用户名可用,即使它存在于数据库中。任何人都可以解决我遇到的问题吗?下面是我的代码。

PHP

    // Define $username
$username=$_POST["emailAddress"];

// Create Connection
$db = new mysqli($server, $user, $password, $database);

// Check Connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}

// SQL query to fetch registerd users and finds user match.
$query = "SELECT email_address FROM users WHERE email_address='$username'";

$result = mysqli_query($db,$query);
$rows = mysqli_num_rows($result);

//if number of rows fields is bigger them 0 that means it's NOT available '
if($rows>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
mysqli_close($db); // Closing Connection

jQuery

$(document).ready(function () {

//when button is clicked
$('[name="checkAvail"]').on("click", function () {
check_availability();
});

});

//function to check username availability
function check_availability() {

//get the username
var username = $('[name="emailAddress"]').val();

//use ajax to run the check
$.post("checkusers.php",
function (result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('.existingUser').html(username + ' is Available');
} else {
//show that the username is NOT available
$('.existingUser').html(username + ' is NOT Available');
}
});

}

HTML

         <div class="form-group">
<button class="btn btn-default" name="checkAvail">Check Availability</button>
<label for="emailAddress" class="col-sm-5 control-label">Email:</label>
<div class="col-sm-4">
<input type="email" class="form-control" id="emailAddress" name="emailAddress" placeholder="Email" autocomplete="off">
</div>
</div>

最佳答案

你的ajax不发送任何数据...所以$_POST["emailAddress"];在你的php中将为空

您需要添加一个数据对象作为$.post的第二个参数

$.post("checkusers.php",{emailAddress : username },function (result) {
// success handing code left out for clarity
});

此外,在允许用户检查输入之前,您应该检查输入是否不为空。向服务器发送无效的空值没有意义。

您可以使用许多简单的 JavaScript 验证插件。

同样,服务器上应该验证用户输入。这是最重要的验证点,因为可以解决 JavaScript 允许发送任何内容

关于php - 使用 Ajax 和 PHP 检查数据库中的现有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30020494/

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