現在,我點擊一個添加按鈕時會彈出一個對話框。內部有2個輸入,將在提交時插入數據庫。有一個下拉列表和一個輸入框。如果已經存在於數據庫中的值輸入到輸入框中,我不希望提交對話框能夠工作。所以基本上,我不希望Supp_ID列中有任何重複的記錄。我怎樣才能做到這一點?這是我到目前爲止。輸入重複記錄時不要插入到數據庫
對話形式:
<div id="dialog-form" title="Add Supplier ID">
<p class="validateTips">All form fields are required.</p>
<!-- Dialog box displayed after add row button is clicked -->
<form >
<fieldset>
<label for="mr_id">MR_ID</label>
<select name="mr_id" id="mr_id_dialog" class="text ui-widget-content ui-corner-all" value="300">
<?php foreach($user1->fetchAll() as $user2) { ?>
<option>
<?php echo $user2['MR_ID'];?>
</option>
<?php } ?>
</select><br><br>
<label for="supplier_id">Supplier ID</label>
<input type="text" name="supp_id" id="supplier_id" class="text ui-widget-content ui-corner-all" value="99">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
的JavaScript:
$("document").ready(function() {
$('#submit').submit(function() {
processDetails();
return false;
});
});
function processDetails() {
var errors = '';
// Validate Supp ID
var supplier = $("#supplier_id [name='supp_id']").val();
if (supplier == "null" || supplier == "") { // check for empty value
errors += ' - Please enter a different Supplier ID\n';
}
// MORE FORM VALIDATIONS
if (errors) {
errors = 'The following errors occurred:\n' + errors;
alert(errors);
return false;
} else {
// Submit form via Ajax and then reset the form
$("#submit").ajaxSubmit({success:showResult}).resetForm();
return false;
}
}
function showResult(data) {
if (data == 'save_failed') {
alert('ERROR. Your input was not saved.');
return false;
} else if (data == 'save_failed_duplicate') {
alert('ERROR. Input data already exists.');
return false;
} else {
alert('SUCCESS. Your input data has been saved.');
return false;
}
}
Insert.php
<?php
$MR_ID = $_POST['MR_ID'];
$Supp_ID = $_POST['Supp_ID'];
$host="xxxxxxxx";
$dbName="xxxx";
$dbUser="xxxxxxxxxxx";
$dbPass="xxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$check_sql = "SELECT Supp_ID FROM Stage_Rebate_Index WHERE Supp_ID = '$Supp_ID'";
$check_sql_query = sqlsrv_query($check_sql, $dbh);
if (sqlsrv_num_rows($check_sql_query) > 0) {
echo "save_failed_duplicate";
@sqlsrv_close($dbh);
return;
} else {
if (sqlsrv_num_rows($check_sql_query) == 0) {
$sql = "INSERT INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, '$Supp_ID')";
if (@sqlsrv_query($sql, $dbh)) {
echo "success";
@sqlsrv_close($dbh);
return;
} else {
echo "save_failed";
@sqlsrv_close($dbh);
return;
}
}
}
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($MR_ID, $Supp_ID));
echo json_encode($result);
?>
化妝** Supp_ID列**在數據庫中是唯一和使用** UPSERT查詢到**避免重複的值。 –