我正在尝试使用以下代码执行“重复用户名”检查。它继续告诉我,用户名是可用的,实际上它不是。有人能告诉我我做错了什么。
FORM
<form method="post" action="scripts/checkusername.php">
<div class="form-group" hidden>
<label for="store">User ID</label>
<input type="text" class="form-control" name="uid" id="uid" value="<?php echo " " . $_SESSION["UserID"] . " "; ?>">
</div>
<div class="form-group">
<label class="control-label">Store URL</label>
<p class="form-control-static"><b><?php echo isset($row['Username']) ? $row['Username'] : NULL; ?></b>.example.com</p>
</div>
<div class="form-group">
<label for="store">Store Name</label>
<input type="text" class="form-control" name="username" id="username" value="<?php echo isset($row['Username']) ? $row['Username'] : NULL; ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="email" class="form-control" name="email" id="email" value="<?php echo isset($row['EmailAddress']) ? $row['EmailAddress'] : NULL; ?>">
</div>
<button type="submit" class="btn btn-prime">Update Details</button>
</form>
SCRIPT
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "users";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['username']))
{
$username = mysql_real_escape_string($_POST['username']);
if (!empty($username))
{
$username_query = mysql_query("SELECT *
FROM users
WHERE Username = '$username'");
$count=mysql_num_rows( $username_query);
if($count==0)
{
echo "Username doesn't exist";
exit;
}
else
{
echo "Username already exists";
exit;
}
}
}
?>
答案 0 :(得分:1)
由于您使用new mysqli
打开数据库连接,因此必须使用mysqli
函数来执行查询,而不是mysql
函数。
if (isset($_POST['username']))
{
$username = $_POST['username'];
if (!empty($username))
{
$username_query = $conn->prepare("SELECT *
FROM users
WHERE Username = ?");
$username_query->bind_param("s", $username);
$username_query->execute();
$count = $username_query->num_rows;
if($count==0)
{
echo "Username doesn't exist";
exit;
}
else
{
echo "Username already exists";
exit;
}
}
}