检查重复项,PHP& MySQL的

时间:2014-09-18 18:43:16

标签: php mysql mysqli duplicates

我有以下代码,完美无缺。如果用户输入的电子邮件地址已存在于数据库中,我希望用户收到错误消息! 谢谢!

 $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);

2 个答案:

答案 0 :(得分: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();

}

另一种确保数据库中不存在重复记录的方法是将您的列设为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

}

使用预准备语句方法更好,更安全。

答案 1 :(得分:0)

使用选择语句检索包含输入电子邮件的行,并检查行数> 0