如果数据库已具有值,但仍获取ID,则如何忽略INSERT


How to ignore INSERT if Database already has the values, but still get the ID?

如果Answer1Text和Answer2Text这两个值已经在数据库中,但仍然从行中获取id(称为AnswerID(主键)?我该怎么做?

我的代码:

$stmt = $conn->prepare("INSERT INTO answers (Answer1Text, Answer2Text) VALUES (?, ?)");
$stmt->bind_param('ss', $text1, $text2);
$stmt->execute();
$answerid = $stmt->insert_id;

重要性表:

答案:AnswerID(PK)、Answer1Text、Answer2Text

我试过看ON DUPLICATE KEY UPDATE,但我既不知道如何使用它,也不认为它是正确的选择。

最好的方法是首先使用SELECT查询来查询数据库:数据是否已经存在?如果是,请拔出ID并使用它来代替插入ID;如果没有,请插入新行。你是对的:ON DUPLICATE KEY UPDATE对此是错误的。