检查数据库中是否已存在电子邮件并添加/更改数据

时间:2015-04-21 11:49:02

标签: mysql sql database

我有一个包含14个数字输入和2个文本输入的表单 - 姓名和电子邮件。有人正在添加数据并将其保存到数据库中 - 我已经完成了。但是当有人使用相同的电子邮件地址第二次添加数据时,数据库应该使用该电子邮件覆盖特定行中的数据。

我在sql中读到了UPDATE,但我不知道如何进行查询,以检查该电子邮件是否存在以及之后是否添加或更新数据。

<?php
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "test";
$quantity = $_POST['quantity'];
$quantity2 = $_POST['quantity2'];
$quantity3 = $_POST['quantity3'];
$quantity4 = $_POST['quantity4'];
$quantity5 = $_POST['quantity5'];
$quantity6 = $_POST['quantity6'];
$quantity7 = $_POST['quantity7'];
$quantity8 = $_POST['quantity8'];
$quantity9 = $_POST['quantity9'];
$quantity10 = $_POST['quantity10'];
$quantity11 = $_POST['quantity11'];
$quantity12 = $_POST['quantity12'];
$quantity13 = $_POST['quantity13'];
$quantity14 = $_POST['quantity14'];
$name = $_POST['name'];
$email = $_POST['email'];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO Results (1paracwierc, 1paracwierc2, 2paracwierc, 2paracwierc2, 3paracwierc, 3paracwierc2, 4paracwierc, 4paracwierc2, 1parapol, 1parapol2, 2parapol, 2parapol2, final, final2, name, email)
VALUES ($quantity, $quantity2, $quantity3, $quantity4, $quantity5, $quantity6, $quantity7, $quantity8, $quantity9, $quantity10, $quantity11, $quantity12, $quantity13, $quantity14, '$name', '$email')";

if ($conn->query($sql) === TRUE) {
    echo "Saved.";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?> 

1 个答案:

答案 0 :(得分:4)

使用insert . . . on duplicate key update。如果您有一个独特的关键词,那么您可以这样做:

create unique index idx_results_name_email (name, email);

然后,数据库将强制执行唯一性。你想要的陈述是:

INSERT INTO Results (1paracwierc, 1paracwierc2, 2paracwierc, 2paracwierc2, 3paracwierc, 3paracwierc2, 4paracwierc, 4paracwierc2, 1parapol, 1parapol2, 2parapol, 2parapol2, final, final2, name, email)
    VALUES ($quantity, $quantity2, $quantity3, $quantity4, $quantity5, $quantity6, $quantity7, $quantity8, $quantity9, $quantity10, $quantity11, $quantity12, $quantity13, $quantity14, '$name', '$email')
    ON DUPLICATE KEY UPDATE 1paracwierc = VALUES(1paracwierc),
                            1paracwierc2 = VALUES(1paracwierc2),
                             . . .
                            final2 = VALUES(final2);