我有多个文本字段,文本字段的数量是由于数据库中有多少数据。两者的输入都是整数,我想要的是当输入到文本字段时,如果输入的数据大于数据库中的值,则会抛出错误 例如 在一个markcheme 输入文本框的数据是给学生的标记,数据库中的数据是该特定问题的最大标记,因此不能超过该值 所以实际上我想比较这些值,如果文本输入值大于它抛出的数据库中的输入值并且错误:)
答案 0 :(得分:0)
很多方法可以解决这个问题,但几乎所有你可以使用javascript解决方案进行客户端检查,PHP用于服务器端...对于前端,你可以查询数据库并输出隐藏输入中的信息然后使用javascript解决方案将文本框的值与匹配的隐藏div的值进行比较。
当文本框失去焦点时,您可以使用AJAX并根据数据库查询文本框中的内容。
当用户最终提交表单时,您还应该使用PHP再次针对daabase验证数字。
所以...需要更多的信息,但上述步骤是你想要做的 - 你如何做到这些取决于你,如果你在尝试上述方法并遇到问题后需要特定的帮助,我们很乐意帮助你。
快乐的编码,祝你好运!
答案 1 :(得分:0)
如果你可以依赖启用了javascript的用户,我会说最容易验证客户端的数据。
你可以这样做:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<input type="text" value="5" name="grade[123]" data-max="10" />
<script type="text/javascript">
$(function() {
$('input[type="text"]').blur(function(e) {
var $this = $(this);
var max = parseInt($this.data('max'), 10);
if (parseInt($this.val(), 10) > max) {
var name = $this.attr('name');
console.error('Value ' + $this.val() + ' in field "' + name + '" exceed its maximum value of ' + max);
$this.focus();
}
})
});
</script>
</body>
</html>
或者您可以使用简单的HTML5 数字字段替换所有这些逻辑:
<input type="number" value="5" name="grade[123]" min="0" max="10" />
显然,人们永远不应该信任他们的用户。您应该始终仔细检查服务器端的数据,并通知用户可能的错误。
这是你可以做的事情:
<?php
if (!empty($_POST)) {
// ...
// fetch max values from the database in the form of
// array(
// id => [max],
// );
$maxValues = array( /* ... */ );
// prepare some error array if you want to show errors next to individual fields
$errors = array();
// ...and then loop through the posted array
foreach ($_POST['grades'] as $id => $value) {
// make sure the submitted value is an integer
if (!ctype_digit($value) && !is_int($value)) {
$errors[$id] = 'Invalid value';
continue;
}
if ((int) $value > (int) $maxValues[$id]) {
$errors[$id] = 'Value cannot be more than ' . $maxValues[$id];
}
}
// assign errors to the view or do whatever is required in your script
// ...
}
理解我在那里做的事情应该不难。基本上,有一个参考数组和要验证的数据数组(注意:您的HMTL字段名称必须在其中包含方括号以充当数组)。然后循环遍历提交的数据并验证参考数组。
就像Ryan Kempt所说,有很多方法可以做到这一点,如果没有您的数据结构的具体示例或者您希望如何向用户呈现错误/异常,那么很难准确地写出来代码。
尽管如此,请看看我们的建议并从那里开始。祝你好运!