简体   繁体   English

使用Javascript将变量传递给PHP MySQL脚本

[英]Passing variable to php MySQL script with Javascript

I borrowed this code from another source. 我从另一个来源借来了此代码。 Now, I am attempting to modify it. 现在,我正在尝试对其进行修改。

I need to pass the contents of $q to my php page and use this as a where clause in my SQL statement. 我需要将$ q的内容传递到我的php页面,并将其用作SQL语句中的where子句。

My Javascript: 我的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>

Inside the html select code I am using: onchange="subject(this.value)" 在我正在使用的html select代码中: onchange="subject(this.value)"

My PHP 我的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 ";

As you can see, I am passing the $q into my SQL statement. 如您所见,我正在将$ q传递到我的SQL语句中。 I understand that intval returns a number, but when I try other types, such as strval, it breaks the script. 我知道intval返回一个数字,但是当我尝试其他类型(例如strval)时,它将破坏脚本。 It als breaks the script when I tried the commented out section above. 当我尝试上面注释掉的部分时,它也会破坏脚本。

When I change the php to: $q=$_GET["q"]; 当我将php更改为: $q=$_GET["q"]; I get the error: form_get.php?q=Reading 500 (Internal Server Error). 我收到错误消息:form_get.php?q =读取500(内部服务器错误)。 This tells me that $q is indeed pulling from the options list, but something else is going on... 这告诉我$ q确实是从选项列表中拉出的,但是还有其他事情在发生...

$q = intval($_GET['subject']);

This looks wrong - should that not be $q = intval($_GET['q']); 这看起来是错误的-应该不是$q = intval($_GET['q']); ?

the problem is with your php you suppose to get the q and not subject 问题是与您的PHP,您想得到q,而不是主题

$q = intval($_GET['q']);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM