2014-09-18 119 views
-3

我有以下代码,它完美地工作。如果他输入的电子邮件地址已经存在于数据库中,我希望用户收到错误消息! 谢谢!检查重复项,PHP和MySQL

$con=mysqli_connect("xxxx.com","xxxx_xxx","xxxx","yyyyy_"); 
// Check connection 
if (mysqli_connect_errno()) { 
echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 


$firstname = mysqli_real_escape_string($con, $_POST['firstname']); 
$lastname = mysqli_real_escape_string($con, $_POST['lastname']); 
$password = mysqli_real_escape_string($con, $_POST['password']); 
$email = mysqli_real_escape_string($con, $_POST['email']); 
$address = mysqli_real_escape_string($con, $_POST['address']); 
$postcode = mysqli_real_escape_string($con, $_POST['postcode']); 
$country = mysqli_real_escape_string($con, $_POST['country']); 
$phonenumber = mysqli_real_escape_string($con, $_POST['phonenumber']); 
$rating = mysqli_real_escape_string($con, $_POST['rating']); 

$sql="INSERT INTO customers (firstname, lastname, password, email, address, postcode, country, phonenumber, rating) 
VALUES ('$firstname', '$lastname', '$password', '$email', '$address', '$postcode', '$country', '$phonenumber', '$rating')"; 

if (!mysqli_query($con,$sql)) { 
die('Error: ' . mysqli_error($con)); 
} 
echo "1 record added"; 

mysqli_close($con); 
+1

在问之前你没有Google吗?使用'mysqli_num_rows()' – 2014-09-18 18:44:36

+1

* snicker *你很荒唐@ Fred-ii- Google太难了。 – 2014-09-18 18:46:56

+1

@JayBlanchard难道不是巧克力棒吗?现在你已经做到了,我现在有了零食。 *士力架* – 2014-09-18 18:47:41

回答

0

使用选择语句检索与输入电子邮件行,检查是否行计数> 0

+1

如果OP的电子邮件列设置为唯一,则会抛出错误。不需要单独的查询。 – 2014-09-18 18:50:40

4

这里,使用prepared statements方法和num_rows()

$con = new mysqli("localhost", "user", "password", "database"); 
if ($con->connect_errno) { 
    echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error; 
} 

$check_email = $con->prepare("SELECT * FROM customers WHERE email=?"); 
    $check_email->bind_param("s", $email); 
    $check_email->execute(); 
    $check_email->store_result(); 
    $row_check = $check_email->num_rows; 

if($row_check > 0) { 

// your error message or make it die. 

$check_email->close(); 
$con->close(); 

} 

的另一种方式,以确保不重复的记录存在于数据库,就是让你的列(S)为UNIQUE


或:

$check_email = mysqli_query($con, "SELECT * FROM customers where email= '".$email."' "); 

$numrows=mysqli_num_rows($check_email); 

if($numrows > 0){ 
    die("Email exists already."); 
} 

else { 

    echo "Does NOT exist."; // continue and insert into DB 

} 

使用准备好的报表方法更好,更安全。