HTML 表单需要知道数据库中有多少条记录


HTML Form needs to know how many records in DB

我有一个HTML表单(PHP),它有一个或两个复选框,具体取决于用户在表单前面的下拉列表中选择的内容。 问题是:

当用户从下拉列表中选择一个选项时,我需要访问 SQL 数据库以找出适合查询的记录数,如果超出限制,则只允许一个复选框,否则为 2。

伪:

Select location dropdown (populated by PHP/SQL );
If onchange.location has less than 50 records 
    show/enable 2 type checkboxes
else 
    show/enable one type checkbox

从我所做的研究来看:

  • 使用 javascript 访问服务器数据库是禁忌,
  • 不能在客户端使用 PHP 完成。
  • 当用户在下拉列表中选择用户时,onchange 事件会触发函数showUser()

    网页:

    <html>
    <head>
    <script>
    function showUser(str) {
      if (str=="") {
        document.getElementById("txtHint").innerHTML="";
        return;
      } 
      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 (xmlhttp.readyState==4 && xmlhttp.status==200) {
          document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
      }
      xmlhttp.open("GET","getuser.php?q="+str,true);
      xmlhttp.send();
    }
    </script>
    </head>
    <body>
    <form>
    <select name="users" onchange="showUser(this.value)">
    <option value="">Select a person:</option>
    <option value="1">Peter Griffin</option>
    <option value="2">Lois Griffin</option>
    <option value="3">Joseph Swanson</option>
    <option value="4">Glenn Quagmire</option>
    </select>
    </form>
    <br>
    <div id="txtHint"><b>Person info will be listed here.</b></div>
    </body>
    </html>
    

    AJAX 请求发送到getuser.php,因此您可以向数据库执行请求。

    getuser.php代码 :

    <?php
    $q = intval($_GET['q']); // your sent parameter by AJAX
    // do your request and process all needed info from DB.
    ?php>
    

    您可以在本教程中找到所有需要的信息。