简体   繁体   English

使用 XMLHttpRequest 将 Javascript 变量发送到 PHP 以查询 MySQL。 不工作

[英]Using XMLHttpRequest to send Javascript variable to PHP to query MySQL. Not working

I'm trying to query my MySQL database.我正在尝试查询我的 MySQL 数据库。 The Javascript code in my html file is ...我的 html 文件中的 Javascript 代码是...

<script>
function getGameNumberOfPlays() { 
   var sentValue1 = Number;   
   var xhttp;
   xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         document.getElementById("gameNumberOfPlays").innerHTML = this.responseText;
      }
   };
   xhttp.open("GET", "numberOfPlays.php", true);
   xhttp.send(sentValue1);
}
</script>

The 'numberOfPlays.php' code is ... 'numberOfPlays.php' 代码是......

<?php
$dbhost =   'localhost';
$dbuser =   'xxx'; 
$dbpwd  =   'xxx'; 
$dbname =   'xxx';

$conn   =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

$p1 = $_GET['sentValue1'];

$sql= "SELECT COUNT(ID) FROM `data` WHERE `gameNumber` =  ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $p1);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_array();
echo "$user[0]";
$conn->close();

?>

The code above produces 0 in my html page.上面的代码在我的 html 页面中生成 0。

However, if I change the code of 'numberOfPlays.php' to ...但是,如果我将“numberOfPlays.php”的代码更改为...

<?php
$dbhost =   'localhost';
$dbuser =   'xxx'; 
$dbpwd  =   'xxx'; 
$dbname =   'xxx';

$conn   =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

$p1 = $_GET['sentValue1'];

$p2 = 171; // or any number that's in the database

$sql= "SELECT COUNT(ID) FROM `data` WHERE `gameNumber` =  ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $p2);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_array();
echo "$user[0]";
$conn->close();

?>

I get the correct number in my html page so it appears that the coding is OK except for how the variable 'sentValue1' is sent and received.我在我的 html 页面中得到了正确的数字,所以除了变量“sentValue1”的发送和接收方式之外,编码似乎是可以的。

I'd be very grateful if anyone could let me know how to change the code so that MySQL query works with the variable 'sentValue1'.如果有人能告诉我如何更改代码以便 MySQL 查询与变量“sentValue1”一起使用,我将不胜感激。

The 'gameNumber' column in the database is configured like this ...数据库中的“gameNumber”列是这样配置的...

Screenshot of column 'gameNumber' “gameNumber”列的屏幕截图

Many thanks.非常感谢。

You did not send the sentValue1 in your xhttp request您没有在 xhttp 请求中发送sentValue1

change:改变:

xhttp.open("GET", "numberOfPlays.php", true);
xhttp.send(sentValue1);

to:至:

let URL = "numberOfPlays.php?sentValue1=<number>"; 
xhttp.open("GET", URL, true); 
xhttp.send();

or:或者:

xhttp.open("GET", "numberOfPlays.php", true);
xhttp.send(sentValue1=<number>);

You can check this link你可以检查这个链接

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

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