防止在php/mysql中插入重复的行 [英] preventing duplicate row insertion in php/mysql
问题描述
如何防止在php mysql中输入重复记录?在插入表之前先验证输入.
how do you prevent the entry of duplicate records in php mysql? validating input before insertion to the table.
我目前正在为我的网站建立一个用户注册部分,但是如果在数据库中找到重复的用户名或电子邮件地址,我想向他们显示一个错误.
i am currently building a user registration section for my website but want to present them with an error if a duplicate username or email address is found in the database.
编辑
这是我到目前为止要插入的行...在这里如何实现这两个答案:
EDIT
This is what I have to far to insert rows... how would I implement both these answers here:
<?php
if (array_key_exists('confirm',$_POST)) {
$Cuser = $_POST['Cuser'];
$Cemail = $_POST['Cemail'];
$Cpassword = $_POST['Cpassword'];
$md5password = md5($_POST['Cpassword']);
mysql_query("INSERT INTO tbl_users (`username`,`email`,`password`)
VALUES ('$Cuser', '$Cemail', '$md5password')");
echo "Thank you. The user <b>".$Cuser." (".$Cemail.")</b> has been successfully added to the database.<p>
<a href='myaccount.php' class='form'>Return</a>";
exit;
}
?>
我猜想我可以在if ... else语句中实现所有功能吗?
I'm guessing that I could implement it all in an if...else statement?
推荐答案
我使用了sql语句和if else语句.
i used the sql statement along with an if else statement.
mysql_select_db($database_speedycms, $speedycms);
$query_usercheck = "SELECT * FROM tbl_users WHERE username='$user' OR email='$email'";
$usercheck = mysql_query($query_usercheck, $speedycms) or die(mysql_error());
$row_usercheck = mysql_fetch_assoc($usercheck);
$totalRows_usercheck = mysql_num_rows($usercheck);
然后
if ( $totalRows_usercheck > 0 )
显示一条错误消息,以防止添加任何重复内容
display an error message to prevent any duplicates from being added
否则允许数据库插入
这篇关于防止在php/mysql中插入重复的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!