2012-08-08 81 views
0

問題檢查重複插入

之前我有一個表tbl_student_courses其中加入2個表studentcourses現在,當數據被插入它是2個IDS 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語法錯誤。

任何機構可以幫助我嗎?

在此先感謝。

+0

你缺少在內部查詢 – 2012-08-08 08:04:45

+0

報價沒有問題相同。 – 2012-08-08 08:16:46

回答

1

也許你缺少一個引號內的查詢值上。 您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']."'準備語句是一個很好的方式不是。考慮使用PDOfilter數據自己,bec。這可以很容易地用於SQL Iinjection因此它是潛在的安全漏洞。

UPDATE:嘗試使用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