【发布时间】:2017-06-06 04:40:59
【问题描述】:
我创建 rand 函数用于生成随机值并与其他值连接并在插入此值之前通过 ajax 显示在文本字段中。但是在这里,在将这个值插入数据库之前,我如何检查这个随机生成值是否存在于数据库中。如果值存在,则再次生成 rand 函数值并再次连接它并在文本框中显示该值。我怎样才能做到这一点?我的代码在下面 index.php
<html>
<head>
<title>Untitled Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var name = $('#name').val();
var year = $('#year').val();
var course = $('#course').val();
var branch_name = $('#branch_name').val();
if ($('#name').val() != "" && $('#year').val() != "" &&
$('#course').val() != "" && $('#branch_name').val() != "") {
$.ajax({
type: "POST",
url: 'roll.php',
data: { name: name, year: year, branch_name: branch_name, course: course },
success: function(response) {
$('#roll').val(response);
}
});
}
}
</script>
</head>
<body>
<form method="post" action="">
<input type="text" name="name" id="name" onChange="my_validate_func()">
<input type="text" name="phone" id="phone" onChange="my_validate_func()">
<input type="text" name="course" id="course" onChange="my_validate_func()">
<input type="text" name="center" id="center" onChange="my_validate_func()">
<input type="text" name="roll" id="roll" value="">
</form>
</body>
</html>
roll.php
<?php
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
$roll =$branch_name.$name.$course.$year.$rand;
//return $roll;
echo $roll;
}
function isValidRoll($roll) {
mysql_connect("localhost","root","");
mysql_select_db("sigma");
$sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
?>
【问题讨论】:
-
发布完整代码。这没有帮助
-
您可以使数据库中的字段唯一。因此,当您尝试进行插入时,您会收到一个错误,并且您会知道该字段已经存在,或者如果您已经获得了行,则只需选择它们。
-
您使用
SELECT...WHERE columnName = rand进行检查。如果返回结果,则表示存在重复,如果没有,则表示尚不存在
标签: javascript php jquery mysql ajax