所以我有一个注册表单,它应该检查电子邮件是否存在,如果存在则不注册,如果不存在则注册。问题是每次我得到你已经是注册用户,即使我什至没有数据库中的任何数据。
这是代码
<?php
error_reporting(E_ALL);
define('DB_HOST', 'localhost');
define('DB_NAME', 'Users');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); //Use MySQLi as MySQL is depreciated.
if (isset($_POST['submit'])) {
//No need for functions, do it all here as otherwise you'll have to declare globals.
if (!empty($_POST['email'])) {
$query = mysqli_prepare($con, "SELECT * FROM Websiteusers WHERE email = ?"); //Preparing the SQL query (We don't insert values directly into the query)
mysqli_stmt_bind_param($query, "s", $_POST['email']); //Bind the email to the SQL query
mysqli_stmt_execute($query); //Execute the query
mysqli_stmt_store_result($query); //Store the results
if(!mysqli_stmt_num_rows($query)) //Is the number of rows 0?
{
//Yes
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
else
{
//No
$query = mysqli_prepare($con, "INSERT INTO WebsiteUsers (firstname,efternamn,email,password) VALUES (?, ?, ?, ?)"); //Preparing the SQL query (We don't insert values directly into the query)
mysqli_stmt_bind_param($query, "ssss", $_POST['firstname'], $_POST['efternamn'], $_POST['email'], $_POST['password']); //Bind the params to the SQL query
mysqli_stmt_execute($query); //Execute the query
echo "YOUR REGISTRATIOfafa";
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Registrera Dig</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table>
<form method="POST" action="test.php">
<tr> <td>Namn</td><td> <input type="text" name="firstname"></td> </tr>
<tr> <td>Efternamn</td><td> <input type="text" name="efternamn"></td> </tr>
<tr> <td>Email</td><td> <input type="text" name="email"></td></tr>
<tr> <td>Lösenord</td><td> <input type="password" name="password"> </td> </tr>
<tr> <td>Bekräfta lösenord </td>
<td><input type="password" name="cpass"></td> </tr>
<tr> <td><input id="button" type="submit" name="submit" value="Skapa konto"></td> </tr>
</form>
</table>
</body>
</html>
可能是什么问题?
最佳答案
看看下面这行
if(!mysqli_stmt_num_rows($query))
并考虑当您没有从数据库返回任何行时的情况。你的代码原则上看起来像
if (!0)
等于 true
,因为感叹号是 not 运算符 - 它会反转它。 if (1)
也为真,但 if (0)
为假(并跳至语句的 else
block ) .
解决方案是简单地删除此 !
,因为您的逻辑目前是相反的。所以这条线看起来像
if (mysqli_stmt_num_rows($query))
为了使您的代码更具可读性,您可以检查它是否大于零,它基本上做同样的事情,但它可以更快地准确理解正在发生的事情。不过,这是个人喜好。
if (mysqli_stmt_num_rows($query) > 0)
关于php - 注册表单返回您已经是注册用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35977519/