使用Javascript将变量传递到php-MySQL脚本


Passing variable to php MySQL script with Javascript

我从另一个源代码借来了这段代码。现在,我正在尝试修改它。

我需要将$q的内容传递到我的php页面,并将其用作SQL语句中的where子句。

我的Javascript:

<script>
  function subject(str) {
    if (str == "") {
      document.getElementById("subject").innerHTML = "";
      return;
    } else { 
      if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
      }
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          document.getElementById("subject").innerHTML = xmlhttp.responseText;
       }
     }
     xmlhttp.open("GET","form_get.php?q="+str,true);
     xmlhttp.send();
    }
  }
</script>

在我正在使用的html选择代码中:onchange="subject(this.value)"

我的PHP

$q = intval($_GET['subject']);
//if (!empty($_GET['q'])){
  //$q = $_GET['q'];
//}
include('../conn/conn.php');
$sql = "select DISTINCT grade FROM primary_skills where subject= $q ";

正如您所看到的,我正在将$q传递到SQL语句中。我知道intval返回一个数字,但当我尝试其他类型(如strval)时,它会破坏脚本。当我尝试上面的注释部分时,它破坏了脚本。

当我将php更改为:$q=$_GET["q"];时,我得到错误:form_get.php?q=读取500(内部服务器错误)。这告诉我$q确实正在从选项列表中退出,但其他事情正在发生…

问题出在您的php中,您假设要获得q而不是主题

$q = intval($_GET['q']);
include('../conn/conn.php');
$sql = "select DISTINCT grade FROM primary_skills where subject= $q ";
$q = intval($_GET['subject']);

这看起来不对——应该不是$q = intval($_GET['q']);吗?