我使用下面的代码将值插入MySQL表中,我需要阻止用户多次为每个priority
插入相同的studentname
值。请问最好的方法是什么?
这是表格:
id studentname title academicdiscipline priority
012345678 TEST, NAME Test title 1 Civil 1
012345678 TEST, NAME Test title 2 Civil 2
012345678 TEST, NAME Test title 3 Civil 3
012345678 TEST, NAME Test title 4 Civil 4
012345678 TEST, NAME Test title 5 Civil 5
代码:
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
$ids = $_POST['id'];
$names = $_POST['studentname'];
$titles = $_POST['title'];
$disciplines = $_POST['academicdiscipline'];
$priorities = $_POST['priority'];
foreach($priorities as $key => $priority) {
if ($priority > 0) {
$query = "INSERT INTO flux_project_selection (id, studentname, title, academicdiscipline, priority)
VALUES ( " . mysql_real_escape_string($ids[$key]) . ",
'" . mysql_real_escape_string($names[$key]) . "',
'" . mysql_real_escape_string($titles[$key]) . "',
'" . mysql_real_escape_string($disciplines[$key]) . "',
" . mysql_real_escape_string($priority) . " )";
$retval = mysql_query($query) or die(mysql_error());
}
}
echo "<p> Added.</p><br />";
}
答案 0 :(得分:2)
使用字段组合
为唯一记录创建索引ALTER TABLE table_name ADD UNIQUE INDEX index_name (field1, field2);
它将允许您添加第一条记录但在重复条目上显示重复条目...用于唯一索引。如果您的项目有此要求,您可以使用try and catch
显示错误消息或使用on duplicate update record
。
答案 1 :(得分:0)
查询学生的最高优先级,然后用1增加。
$queryMaxPriority = 'select max(priority) from flux_project_selection where id = STUDENT_ID;
$priority_no = $queryMaxPriority + 1;
我在我开发的一些应用程序中使用了这个。
<强>更新强>
$priority = 'select count(priority) from flux_project_selection where id = STUDENT_ID and priority = PRIORITY';
if (count($priority>0)){
//send some error message in your page.
}