检查数据库中是否已存在记录 [英] Check if record already exists in database
本文介绍了检查数据库中是否已存在记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
将联系人插入数据库但不会不想复制已经存在的联系人
你好.在插入重复之前,我正在尝试检查电子邮件是否已存在.
Hello. I'm trying to check if an email already exists before I insert a duplicate.
所以我需要检查数据库中是否存在电子邮件地址,如果存在,则输出一条消息,说明它已经存在.否则我想将记录插入到数据库中.
So I need to check the database for the presence of the email address and if it exists ouput a message saying it already exists. Otherwise I want to insert the record into the database.
这是我现在用来插入电子邮件的代码,但我不确定如何检查数据库是否存在.
Here is the code I use to insert the email now, but I'm not sure how to check the database for existence.
$addEmailQuery = sprintf("INSERT INTO `subscribe`(`Email`) VALUES('%s')",
mysql_real_escape_string($_POST['inputEmail']));
$addEmailResult = mysql_query($addEmailQuery);
if($addEmailResult){
echo 'Email successfully submitted';
} else{
echo 'Sorry, we could not submit your email. Please try again.';
}
有人知道我会怎么做吗?
Anyone know how I would do this?
推荐答案
已最初的答案会在多用户环境中造成问题.
EDITED: The initial answer will pose problems in a multi-user environment.
你应该喜欢
INSERT ... ON DUPLICATE KEY UPDATE
按照这个答案 使其正确.
原帖:
if(mysql_num_rows(mysql_query("SELECT * FROM subscribe WHERE Email = '".mysql_real_escape_string($_POST['inputEmail'])."'")))
{
echo "already submitted";
}
else
{
$addEmailQuery = sprintf("INSERT INTO `subscribe`(`Email`) VALUES('%s')",
mysql_real_escape_string($_POST['inputEmail']));
$addEmailResult = mysql_query($addEmailQuery);
if($addEmailResult)
{
echo 'Email successfully submitted';
}
else
{
echo 'Sorry, we could not submit your email. Please try again.';
}
}
这篇关于检查数据库中是否已存在记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文