我是php新手。我想知道如何在我的电子邮件字段中添加重复检查。
function email_exists($email){
global $db;
$query = "SELECT email FROM student";
$statement = $db->prepare($query);
$statement->execute();
$results = $statement->fetchAll();
foreach ($results as $key => $result) {
if ($result['email'] == $email){
return true;
}
}
return false;
}
我做了这个功能,但它有效但我有一个问题,当我只更新我的form.php的名称,如果电子邮件在字段中保持相同,则会出错。我想知道如何解决这个问题,如果我只更新名称而不是电子邮件。
答案 0 :(得分:1)
尝试此查询:
$sql = "SELECT email, COUNT(*) AS count FROM student GROUP BY email HAVING count > 0 ORDER BY count DESC;";
答案 1 :(得分:1)
function email_exists($email){
global $db;
$query = "SELECT email FROM student WHERE email=:email";
$stmt = $db->prepare($query);
$stmt->bindParam(":email", $email);
$stmt->execute();
if ($stmt->rowCount() > 0) {
return true;
} else {
return false;
}
}
答案 2 :(得分:1)
请试试这个:
// @param email, id of updating record
function email_exists($email, $id){
global $db;
$query = "SELECT email FROM student WHERE id !=".$id;
$statement = $db->prepare($query);
$statement->execute();
$row_count = $statement->num_rows;// get total number of rows
if($row_count > 0)
{
// record exists
return true;
}
return false;
}