我正在开发一个预订系统,我需要为每个预订生成一个唯一ID,并在用户点击"添加新预订"
时将其显示在模式内的表单上我使用ajax和SQL来做到这一点,但有时我会得到重复的id。我所做的是每次点击按钮我都会将id插入表格
那是我的代码
<script>
function showId() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("show-id").defaultValue=this.responseText;
}
}
xmlhttp.open("GET","getid.php?=",true);
xmlhttp.send();
}
</script>
<script>
$(function () {
$('#openModal').on('click', function () {
showId();
var mx_val=$("#show-idi").val();
$.ajax({
type: "POST",
url: "insert-id.php",
data: {mx_val:mx_val},
dataType: "JSON",
success: function(data) {
/* $("#message").html(data); */
getDu();
/* $("p").addClass("alert alert-success");*/
},
error: function(err) {
$("#message").html("Saved!");
$("p").addClass("alert alert-success");
console.log(err);
}
});
});
});
</script>
插入-id.php
<?php
include('db.php');
$mx_val=$_POST['mx_val'];
require_once("dbcontroller.php");
$db_handle = new DBController();
$query ='SELECT max(mx_val) from mxvalue';
$results = $db_handle->runQuery($query);
foreach($results as $references) {
$maxvalue = $references["max(mx_val)"] +1;
}
$stmt = $DBcon->prepare("INSERT INTO mxvalue (mx_val) VALUES ('$maxvalue')");
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Problem occured.";
echo json_encode($error);
}
getid.php
<?php
$con = mysqli_connect('','','','');
if (!$con) { die('Could not connect: ' . mysqli_error($con));
} mysqli_select_db($con,"ajax_demo");
$sql="SELECT max(mx_val) from mxvalue";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$maxid = $row["max(mx_val)"] +1;
?><?php echo $maxid; ?><?php } mysqli_close($con);
?>
答案 0 :(得分:1)