我已经在Google上搜索了2个星期,但没有任何效果。我想知道的是如何检查我的MySQL数据库表中是否存在给定的用户名。表名是用户。但它似乎绕过了我的if语句,并且正确地向前添加用户名,导致我的表具有相同用户名的副本。我尝试过很多代码和很多方法。一直在使用Mysqli,因为这是我们现在应该使用的。我可以给你我尝试过的任何方法,但这是我第100次再次尝试的最新方法。请知道,我知道这还没有为防范SQL注入做好充分准备,我现在还不担心。我只是想让这个东西先工作,然后我会添加安全性。 另外需要注意的是,我的数据库登录信息存储在名为“credentials.php”的单独php文件中。 提前致谢。代码:
<?php
$password1 = ($_POST['pass1']);
$password2 = ($_POST['pass2']);
$firstname = ($_POST['fname']);
$lastname = ($_POST['lname']);
$username = ($_POST['user']);
$email = ($_POST['email']);
/*
include_once 'credentials.php';
$dbhandle = new mysqli($db_hostname, $db_username, $db_password, $db_database);
*/
// Check if any fields are empty
if (empty($_POST['fname']) or empty($_POST['lname']) or empty($_POST['user']) or empty($_POST['email']) or empty($_POST['pass1']) or empty($_POST['pass2'])){
?>
<div class="ERRORBOX">
<?php
// Empty Fields ERROR
echo "You must enter data into ALL of the fields to register. Please try again.";
header( "refresh:5;url=../index.php" );
?>
<p>You will be redirected in <span id="counter">5</span> second(s).</p>
<script type="text/javascript">
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)<=0) {
location.href = 'login.php';
}
i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
</script>
</div>
<?php
} else {
// Check if passwords match
if ($password1 !== $password2) {
?>
<div class="ERRORBOX">
<?php
// Password mismatch ERROR
echo "You entered two different passwords! Please try again.";
header( "refresh:5;url=../index.php" );
?>
<p>You will be redirected in <span id="counter">5</span> second(s).</p>
<script type="text/javascript">
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)<=0) {
location.href = 'login.php';
}
i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
</script>
</div>
<?php
} else {
// Create connection
include_once 'credentials.php';
$conn = new mysqli($db_hostname, $db_username, $db_password, $db_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if username exists <<<THIS IS WHERE I AM HAVING TROUBLE<<<<<
$username = ($_POST['user']);
$query = mysqli_query("SELECT * FROM users WHERE username='$username'");
if(mysqli_num_rows($query) > 0){
echo "That username already exists.";
$conn->close();
}
else{
//IT JUST SKIPS THE CODE ABOVE AND GOES STRAIGHT TO THE ONE BELOW
$firstname = ($_POST['fname']);
$lastname = ($_POST['lname']);
$username = ($_POST['user']);
$email = ($_POST['email']);
$password = ($_POST['pass1']);
$ipaddress = $_SERVER['REMOTE_ADDR'];
// Create connection
include_once 'credentials.php';
$conn = new mysqli($db_hostname, $db_username, $db_password, $db_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$sql = "INSERT INTO users (`id`, `username`, `password`, `sign_up_date`, `email`, `email_activation`, `permit`, `status`, `first_name`, `last_name`, `dob`, `ipv4`) VALUES (NULL, '$username', '$password', NOW(), '$email', '0', 'c', 'a', '$firstname', '$lastname', '1985-01-01', '$ipaddress')";
if ($conn->query($sql) === TRUE) {
header('Location: ../success.php');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
}
}
?>
答案 0 :(得分:2)
首先,当您希望数据库表中的行的值仅在您需要将该列指定为UNIQUE
时才会出现。所以首先改变users
表,如下所示:
ALTER TABLE users CHANGE COLUMN username username VARCHAR(255) NOT NULL UNIQUE;
在您完成此操作后,如果您的脚本尝试在包含已使用的用户名的数据库中插入一行,则该行不会插入且您不会重复。但这还不够,您需要一种方法来通知用户他们想要的用户名已经在使用,以便您的PHP脚本进入。
您的脚本无法正常工作,因为您在没有数据库连接对象的情况下调用mysqli_query
。
您可以通过两种方式致电mysql_query
:
mysqli_query($conn, "SELECT * FROM users WHERE username='$username'");
$conn->query("SELECT * FROM users WHERE username='$username'");
您在程序样式中调用mysqli_query
而不给它提供连接对象。将其更改为上述之一,它将起作用
答案 1 :(得分:1)
我强烈建议您只在表格列中添加一个UNIQUE约束。
在MySQL中运行以下查询:
ALTER TABLE users ADD CONSTRAINT ux_username UNIQUE (username)
现在不要进行任何检查,只需插入新用户并检查$conn->error()
。
$sql = "INSERT INTO users (`id`, `username`, `password`, `sign_up_date`, `email`, `email_activation`, `permit`, `status`, `first_name`, `last_name`, `dob`, `ipv4`) VALUES (NULL, ?, ?, NOW(), ?, '0', 'c', 'a', ?, ?, '1985-01-01', ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss', $username, $password, $email, $firstname, $lastname, $ipaddress);
$stmt->execute();
if (empty($conn->error())) {
header('Location: ../success.php');
exit; //remember to exit after redirections
} else {
echo 'Username already exists.';
}
此外,我更改了您的代码以正确插入数据。插入原始用户输入是危险的,因为可能存在松散的单引号或分号。
答案 2 :(得分:1)
您以错误的方式使用了mysqli_query 要么使用
$query = mysqli_query($conn,"SELECT * FROM test WHERE username='$username'");
或使用
$query = $conn->query("SELECT * FROM test WHERE username='$username'");
答案 3 :(得分:0)
向表中添加唯一约束。
import 'rxjs/Rx';
这样可以防止重复插入。你仍然应该试着找出你遇到mysqli_num_rows问题的原因。我建议你手动运行查询,看它是否返回结果。
答案 4 :(得分:0)
找到解决方案。我认为提出解决方案的人删除了他的答案。所以我会在这里发布:(顺便说一下,谢谢大家。你的答案也很有帮助。)
<?php
$password1 = ($_POST['pass1']);
$password2 = ($_POST['pass2']);
$firstname = ($_POST['fname']);
$lastname = ($_POST['lname']);
$username = ($_POST['user']);
$email = ($_POST['email']);
// Check if any fields are empty
if (empty($_POST['fname']) or empty($_POST['lname']) or empty($_POST['user']) or empty($_POST['email']) or empty($_POST['pass1']) or empty($_POST['pass2'])){
?><div class="ERRORBOX"><?php
// Empty Fields ERROR
echo "You must enter data into ALL of the fields to register. Please try again.";
header( "refresh:5;url=../index.php" );
?>
<p>You will be redirected in <span id="counter">5</span> second(s).</p>
<script type="text/javascript">
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)<=0) {
location.href = 'login.php';
}
i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
</script>
</div>
<?php
} else {
// Check if passwords match
if ($password1 !== $password2) {
?><div class="ERRORBOX"><?php
// Password mismatch ERROR
echo "You entered two different passwords! Please try again.";
header( "refresh:5;url=../index.php" );
?>
<p>You will be redirected in <span id="counter">5</span> second(s).</p>
<script type="text/javascript">
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)<=0) {
location.href = 'login.php';
}
i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
</script>
</div>
<?php
} else {
// Create connection
include_once 'credentials.php';
$conn = new mysqli($db_hostname, $db_username, $db_password, $db_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if username exists
$username = ($_POST['user']);
$qry="SELECT * FROM users WHERE username='".$username."'";
$query = mysqli_query($conn, $qry);
if(mysqli_num_rows($query) > 0){
?><div class="ERRORBOX"><?php
echo "That username already exists.";
?></div><?php
}else{
// Check if email exists
$email= ($_POST['email']);
$qry="SELECT * FROM users WHERE email='".$email."'";
$query = mysqli_query($conn, $qry);
if(mysqli_num_rows($query) > 0){
?><div class="ERRORBOX"><?php
echo "That email is already registered.";
?></div><?php
$conn->close();
}else{
$firstname = ($_POST['fname']);
$lastname = ($_POST['lname']);
$username = ($_POST['user']);
$email = ($_POST['email']);
$password = ($_POST['pass1']);
$ipaddress = $_SERVER['REMOTE_ADDR'];
// Create connection
include_once 'credentials.php';
$conn = new mysqli($db_hostname, $db_username, $db_password, $db_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
$sql = "INSERT INTO users (`id`, `username`, `password`, `sign_up_date`, `email`, `email_activation`, `permit`, `status`, `first_name`, `last_name`, `dob`, `ipv4`) VALUES (NULL, '$username', '$password', NOW(), '$email', '0', 'c', 'a', '$firstname', '$lastname', '1985-01-01', '$ipaddress')";
if ($conn->query($sql) === TRUE) {
header('Location: ../success.php');
exit;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
}
}
}
?>