我必须对我的代码做些啥,以便它只会在数据库中不存在电子邮件的情况下创建帐户? [复制]
Posted
技术标签:
【中文标题】我必须对我的代码做些啥,以便它只会在数据库中不存在电子邮件的情况下创建帐户? [复制]【英文标题】:What do I have to do to my code so it will only create the account if the email doesn't already exist in the Database? [duplicate]我必须对我的代码做些什么,以便它只会在数据库中不存在电子邮件的情况下创建帐户? [复制] 【发布时间】:2014-10-10 08:44:30 【问题描述】:<?php
$errorMessage = "";
// start the session and register the session variables
session_start("ProtectVariables");
// get the command value (use request since both post and get are used
$firstname = $_POST['firstNameZ'];
$lastname = $_POST['lastNameZ'];
$password = $_POST['passwordZ'];
$email = $_POST['emailZ'];
$sql = "SELECT email FROM account WHERE email='" . $email . "'";
$result = mysql_query($sql,$db);
while ($myrow = mysql_fetch_array($result))
if ($email == $myrow['email'])
$errorMessage = "Account with that email already exists";
else
$errorMessage = "Email doesn't match!";
if ($_POST['submit'])
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
?>
当我填写表格并点击提交时,即使电子邮件相同,它也只是插入到数据库中。我尝试将带有提交按钮的 if 语句放入 while 循环中,但这也不起作用。
【问题讨论】:
【参考方案1】:您可以更改条件以检查错误消息是否已填写:
if ($_POST['submit'] && $errorMessage == "Email doesn't match")
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
【讨论】:
if($_POST['submit'] && $errorMessage == "Email doesn't match!")
感谢您的帮助 dehrg!不幸的是,错误消息仍然出现 - “该电子邮件的帐户已经存在”。此外,即使电子邮件不同,它也不会向数据库添加任何内容。我不确定出了什么问题。你能再帮帮我吗?
gab06 是正确的!即使您成功了,我也没有看到您正在设置错误消息(考虑到变量的名称,这是不好的做法)请参阅我修改后的答案【参考方案2】:
使用mysql_num_rows
函数来检查用户是否已经存在于数据库中。使用下面的代码
<?php
$errorMessage = "";
// start the session and register the session variables
session_start("ProtectVariables");
// get the command value (use request since both post and get are used
$firstname = $_POST['firstNameZ'];
$lastname = $_POST['lastNameZ'];
$password = $_POST['passwordZ'];
$email = $_POST['emailZ'];
$sql = "SELECT email FROM account WHERE email='" . $email . "'";
$result = mysql_query($sql,$db);
if(mysql_num_rows($result)==0)
if ($_POST['submit'])
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
else
echo "the user with this email address already exist";
?>
希望对你有帮助
【讨论】:
以上是关于我必须对我的代码做些啥,以便它只会在数据库中不存在电子邮件的情况下创建帐户? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
Html 列表标签在 android textview 中不起作用。我能做些啥?