我想防止用户使用php输入重复记录(至少警告它们)。尽管输入了不同的值并警告重复输入,但下面的代码从组合框( Txt_Gen )中回显了相同的代码。表中的行是动态生成的。因此它使用相同的ID,这是问题的根本原因。请帮忙。
这是代码:
<script type="text/javascript">
// Add rows to table //
function addRow1(tableID)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
var gensel = []; // array //
//getting the value of the combobox //
function myFunction1(form)
{
var gval = document.getElementById('Txt_Gen').value;
//var gval = form.Txt_Gen.options[form.Txt_Gen.options.selectedIndex];
var a = gensel.indexOf(gval);
//alert(a);//
if ( a==-1 ) {
gensel.push(gval);
} else {
alert('Duplicate Entry'); // Displays Error Message every time //
}
}
</script>
</head>
<body>
<!-- DB Query for populating the combo box -->
<?Php $genquery= " SELECT GENCODE, DESCRIPTION FROM xxxx";?>
<!-- HTML Part -->
<div id="container">
<form action="indent_dml.php?t=R" class="register" method="POST">
<div id="Layer_Ind_Container" >
<!-- Btn_Add is used to add row to the table -->
<input type="button" id="Btn_Add" name="Btn_Add" value="Add Record" onClick="addRow1('Table_IndNew');" />
<input type="submit" id="Btn_Submit" name="Btn_Submit" value="Submit" >
</div>
<table id="Table_IndNew">
<tr>
<td>
<select name="Txt_Gen[]" size="1" id="Txt_Gen" onchange="myFunction1(this.form)">
<option value=''>--- Select ---</option>
<?php $listemp = $dbo->query($genquery);
while ($rowemp = $listemp->fetch(PDO::FETCH_ASSOC))
{?>
<option value="<?php echo $rowemp['GENCODE']?>"><?php echo $rowemp['DESCRIPTION']?></option>
<?php } ?>
</select>
</td>
<!-- Some other elements are also present in the table such as quantity etc -->
</tr>
</table>
</form>
</div>
</body>
<!-- HTML part Ends -->
答案 0 :(得分:0)
我个人建议使用PDO(php数据对象)来执行此操作,但是由于不确定的上下文太多,我不确定您实际上要实现什么目标?这将连接到某种数据库吗?您设法连接到它了吗?如果是这样,您可以使用PDO进行简单计数以检查数据库
$duplicate = "SELECT COUNT(table) AS num FROM table WHERE [whatever you don't
want to be duplicated] = :btn-add"; // where you bind the input from HTML field
$stmt = $pdo->prepare($duplicate);
$stmt->bindValue(':btn-add', $duplicate);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('That table exists already!');
}
但这在很大程度上取决于您要实现的目标?这就是我解释您要做什么的方式,我建议您在此阅读PDO。 LINK尽管要写出不清楚的答案很困难,但请尝试更加具体地询问您的问题