插入前检查重复项


Check for duplication before insertion

>问题

我有一个表tbl_student_coursesstudent连接 2 个表,现在courses插入数据时它是 2 个 id course_idstudent_id的组合。我只是希望tbl_student_courses不会重复这种组合.

法典

foreach($_POST['sel_course'] as $val) {
$query_std_course = "
  INSERT INTO
    `tbl_student_courses`
  SET
    `course_id` = '".$val."',
    `std_id` = '".$_POST['std']."',
  WHERE NOT EXISTS (
    SELECT * FROM `tbl_student_courses` WHERE course_id=$val AND std_id=$std
  )";
}

帮助

此查询给出SQL语法错误。

有人可以帮助我吗?

提前谢谢。

可能您缺少引号一个内部查询值。SQL查询应如下所示

$sql = "
  INSERT INTO
    `tbl_student_courses`
  SET
    `course_id` = '".$val."',
    `std_id` = '".$_POST['std']."',
  WHERE NOT EXISTS (
    SELECT * FROM `tbl_student_courses` WHERE course_id='".$val."' AND std_id='".$std."'
  )";

注意:在数据库中插入未准备好的语句(如std_id = '".$_POST['std']."')不是一个好方法。bec,请考虑自己使用PDOfilter数据。这可以很容易地用于SQL Iinjection因此它是潜在的安全漏洞。

更新:尝试使用ON DUPLICATE KEY UPDATEINSERT IGNORE INTO table

您可以找到有关实施的更多信息 - http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html

并阅读有关拟议实施的信息 - http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html

您查找的 SQL 语法是 MERGE 语句,或在您的平台上等效

http://en.wikipedia.org/wiki/Merge_(SQL)