现在的问题是,代码无法检查用户名是否已经被占用,有没有代码可以检查用户名是否已经在数据库中被占用?
我正在试验我的一些代码,然后可能还在 Stack Overflow 中搜索了有关此问题的信息。我试过这个solution但显然它给了我错误。当我尝试过时,警告:
mysql_query() expects parameter 2 to be resource, object given in C:... on line ...
和问题
mysql_num_rows() expects parameter 1 to be resource, null given in C:... on line ...
我实际上正在寻找这个问题的解决方案或如何解决这个问题的教程。
我的代码:
<?php
require_once("functions.php");
require_once("db-const.php");
session_start();
if (logged_in() == true) {
redirect_to("profile.php");
}
?>
<?php
?>
<html>
<head>
<title>Prospekt Member Area</title>
</head>
<body>
<h1> Register Here </h1>
<h2>© Kirk Niverba</h2>
<hr />
<!-- The HTML registration form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
First name: <input type="text" name="first_name" /><br />
Last name: <input type="text" name="last_name" /><br />
Email: <input type="type" name="email" /><br />
<input type="submit" name="submit" value="Register" />
<a href="login.php">Already have an account?</a>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['first_name']) || empty($_POST['last_name']) || empty($_POST['email'])) {
echo "Please fill all the fields!";
}
elseif (isset($_POST['submit'])) {
## connect mysql server
$mysqli = new mysqli(localhost, root, "", loginsecure);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
## query database
# prepare data for insertion
$username = $_POST['username'];
$mainpass = $_POST['password'];
$password = hash('sha256', $mainpass);
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
# check if username and email exist else insert
// u = username, e = emai, ue = both username and email already exists
$user = $_POST['username'];
$usernamecheck=mysql_query("SELECT username FROM users WHERE username='$user'", $mysqli);
if (mysql_num_rows($usernamecheck)>=1){
echo $user." is already taken";
}
else{
# insert data into mysql database
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `first_name`, `last_name`, `email`)
VALUES (NULL, '{$username}', '{$password}', '{$first_name}', '{$last_name}', '{$email}')";
if ($mysqli->query($sql)) {
header("Location: checklogin.php?msg=Registered Successfully!");
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
}
}
}
?>
<hr />
</body>
</html>
最佳答案
在出现错误的行中,将“mysql_query”替换为“mysqli_query”,将“mysql_num_rows”替换为“mysqli_num_rows”。这是因为您不能将 mysql 调用与 mysli 连接混合使用。
关于PHP 和 MySQL - 检查用户名是否已被占用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38671619/