如果您遇到类似问题,请检查已接受的答案。
首先,我知道有一些像这样的类似问题,但没有能够帮助我的问题。
我正在尝试检查数据库中是否已存在用户名或电子邮件,我已将它们设置为数据库中的唯一,但是想要这样,我可以显示用户名/电子邮件的单独错误。
现在它只是在尝试注册时输出一个白页,我花了好几个小时试图自己弄清楚..任何帮助都将受到高度赞赏。
我添加了有关有问题的代码的评论,我无法开始工作。
这是我的代码:
<?php
// Include database connection and functions here.
include 'db_connect.php';
include 'functions.php';
// The hashed password from the form
$password = $_POST['p'];
// Create a random salt
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
// Create salted password (Careful with the chilli)
$username = $_POST['username'];
$email = $_POST['email'];
//Start of problematic code
$check_stmt = $mysqli->prepare("SELECT * FROM members WHERE username=? OR email=?");
$check_stmt->bind_param('ss', $username, $email);
$check_stmt->execute();
$check_result = $check_stmt->get_result();
while ($row = $check_result->fetch_assoc()) {
if ($row->num_rows > 0)
{
if ($row['username'] > '')
{
header("Location: '..\..\..\?RegUserExsist=1'");
}
else if ($row['email'] > '')
{
header("Location: '..\..\..\?RegEmailExsist=1'");
}
}
//end of problematic code
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
header("Location: '..\..\..\?RegInvalidEmail=1'");
}
else if (empty($username))
{
header("Location: '..\..\..\?RegInvalidUser=1'");
}
else if (empty($password))
{
header("Location: '..\..\..\?RegInvalidPass=1'");
}
else
{
$password2 = hash('sha512', $password.$random_salt);
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)"))
{
$insert_stmt->bind_param('ssss', $username, $email, $password2, $random_salt);
// Execute the prepared query.
$insert_stmt->execute();
header("Location: '..\..\..\?success=1'");
}
else
{
header("Location: '..\..\..\?regfailed=1'");
}}}
?>
答案 0 :(得分:1)
我使用PDO并且我有这个代码检查是否已经使用了用户名
<?php
/* Create a new PDO object with database connection parameters */
$dbh = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
// Create statement object
$stmt = $dbh->prepare("SELECT username FROM users WHERE username = :username");
$stmt->bindValue(":username", $user);
$stmt->execute();
if($stmt->rowCount() != 0) {
$this->setError('<span class="bold">Username</span> you have selected has already been used by another member in our database. Please choose a different Username!');
}