我想阻止用户注册已在我的表格中设置的电子邮件地址。我是这样做的:
$emailcheck = $bdd->prepare('SELECT COUNT(*) FROM ' . DB_TABLE . ' WHERE MATCH(email) AGAINST '.$_POST['email'].' ');
$emailcheck->execute();
$emailcheckrows = $emailcheck->fetch();
if ($emailcheckrows > 0) {
$_SESSION['err_msg']="This email address is already registered";
$error=true;
$emailcheck->closeCursor();
}
但这不起作用。我已经尝试了几乎所有的东西(也有LIKE,=和in-array)。 "如果"我输入已提交的电子邮件时未执行。
有什么想法吗?谢谢
答案 0 :(得分:-1)
你可以将它用作一个简单的函数,如:
class Validation {
public static function emailUnique($conn, $email)
{
$sql = "SELECT email FROM formular WHERE email = '".$email."'";
$emailUnique = $conn->query($sql);
return (boolean) $emailUnique->num_rows;
}
}
如果找到条目,则返回true
,如果没有,则返回false
,然后您可以在脚本中调用此函数。我已经将它与bootstrap-alerts一起使用了:
$errorField = "";
$labelClass = array(
"emailUnique"=>"",
);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$errorMessages["emailUnique"] = Validation::emailUnique($conn ,$email);
$DisplayErrorForm = array();
$hasErrors = false;
$formErrorMessage = "";
foreach ($labelClass as $key=>$value) {
if($errorMessages[$key]){
$labelClass[$key] = "has-error";
$hasErrors = true;
$DisplayErrorForm["emailUnique"] = array("style" => "red", "text" => "Email is already taken");
if($key == "emailUnique"){
$formErrorMessage .= "<li style='" . $DisplayErrorForm["emailUnique"]["style"] . "'>" . $DisplayErrorForm["emailUnique"]["text"] . "</li>";
}
}
}
if(count($DisplayErrorForm)) {
$errorField = "<div class=\"alert alert-danger\">".
"<strong>Whoops!</strong> There were some problems with your input.<br><br>".
"<ul>".$formErrorMessage."</ul>".
"</div>";
}
if (!$hasErrors) {
//Do the database input
然后在你的html部分调用$ errorField
<div>
<?php echo $errorField; ?>
</div>
答案 1 :(得分:-1)
答案是绑定值并使用rowCount()。它使用以下代码:
$emailcheck = $bdd->prepare('SELECT * FROM ' . DB_TABLE . ' WHERE email = ?');
$emailcheck->bindValue( 1, $_POST['email'] );
$emailcheck->execute();
if ($emailcheck->rowCount() > 0) {
$_SESSION['err_msg']="e-mail addresse already registered";
$erreur=true;
$emailcheck->closeCursor();
header ('Location: form.php');
}
查询而不是准备可能更容易..