2012-03-23 136 views
0

我有多个文本字段,文本字段的数量是由于数据库中有多少数据。两者的输入都是整数,所有我想要的是将值输入到文本字段时,如果输入的数据大于数据库中的值 例如 中的markscme 输入到文本框是给学生的标记,数据库中的数据是该特定问题的最大标记,因此它不能超过该值,因此实际上我想比较这些值,如果文本输入值大于在数据库中它抛出和错误:)PHP比较数据库与文本框中的值

+1

向我们展示一些代码,mate – dotoree 2012-03-23 15:25:38

回答

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说的,有很多方法可以做到这一点,没有数据结构的特定例子,或者你想如何将错误/异常呈现给用户,这很难写给你确切的代码。

然而,看看我们的建议,并从那里开始。祝你好运!

0

很多方法来解决这个问题,但几乎所有可以使用JavaScript解决方案进行客户端检查和PHP的服务器端...前端您可以查询数据库并在隐藏输入中输出信息然后使用JavaScript解决方案将文本框的值与匹配隐藏div的值进行比较。

当文本框失去焦点时,您可以使用AJAX并根据数据库查询文本框中的内容。

当用户最终提交表单时,您还应该再次使用PHP对daabase进行验证。

因此...需要更多信息,但上述步骤是您要做的 - 您如何去做是取决于您,如果在尝试上述方法并遇到问题后需要特定帮助我们很乐意为您提供更多帮助。

快乐的编码和祝你好运!

相关问题