PHP / MySQL:如果记录已存在(无更新),如何返回信息

时间:2015-06-21 15:05:35

标签: php mysql ajax insert duplicates

我正在使用以下内容将新行插入MySQL数据库。 对此的查询存储在PHP文件(ajax.php)中,输入值通过jQuery中的Ajax调用传递给它。

一切都按预期工作但如果电子邮件已经在数据库中,我想向用户返回一条消息。 我知道如何使用 ON DUPLICATE KEY 来更新数据库行,但是有人可以告诉我如何检查这个并回显一些已存在的内容(即没有更新)它)? (电子邮件是一个主键,因此我只需要检查此列。)

我的PHP:

$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
    die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$dob = $_POST["dob"]; 
$sql = "INSERT INTO Users (email, dob) VALUES ('" . $email . "', '" . $dob . "')"; 
if ($conn->query($sql)){ 
    echo 'DB Update successful'; 
}else{ 
    echo 'DB Update failed'; 
} 
$conn->close();

2 个答案:

答案 0 :(得分:3)

在插入之前,您只需要进行简单的SELECT调用。

$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
    die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$dob = $_POST["dob"];
$sql = "SELECT email FROM Users WHERE email = " .$email;
$query = $conn->query($sql);
if (mysqli_num_rows($query) > 0){
    echo "There exists an user with this email";
}
else {
    $sql = "INSERT INTO Users (email, dob) VALUES ('" . $email . "', '" . $dob . "')";
    if ($conn->query($sql)) {
        echo 'DB Update successful';
    }
    else {
        echo 'DB Update failed';
    };
}

$conn->close();

答案 1 :(得分:1)

简单的方法就是使用您尝试存储的相同电子邮件来计算表中条目的出现次数。计数而不是SELECT意味着它更快,只返回一个计数而不是一个完整的行,然后你必须查看或计算结果中的行。

$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
    die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$dob = $_POST["dob"]; 

$countResult = $Conn->query("Select Count(email) FROM Users WHERE email = '$email'");
$Count = $countResult->fetch_row();
$countResult->close();

if ( $Count[0] > 0 ) {
    // its already there so do whatever you want in this case
} else {

    $sql = "INSERT INTO Users (email, dob) VALUES ('" . $email . "', '" . $dob . "')"; 
    if ($conn->query($sql)){ 
        echo 'DB Update successful'; 
    }else{ 
        echo 'DB Update failed'; 
    } 
}
$conn->close();