简体   繁体   中英

Rewriting code from using GET-method to using POST-method

For security reasons I want to change my code from using GET to using POST. The first function (getcurrenthighscoreGet) works perfectly (it returns a string), but the second function (getcurrenthighscorePost) which should give the same result, returns an empty string with zero length. Does anyone have a clue what is going wrong in the second function?

 function getcurrenthighscoreGet(username) { xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { document.getElementById("tdScore").innerHTML = parseInt(this.responseText); } }; xhttp.open("GET", "getcurrenthighscore.php?q1=" + username, true); xhttp.send(); } function getcurrenthighscorePost(username) { var xhttp = new XMLHttpRequest(); var url = "getcurrenthighscore.php"; var params = "q1=" + username; xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { document.getElementById("tdScore").innerHTML = parseInt(this.responseText); } }; xhttp.open("POST", url, true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send(params); } 

The php function that is called:

<?php
require_once "connect.php";
$sql = "SELECT highscore FROM users WHERE username = ?";
$stmt = $con->prepare($sql);
if ($stmt->bind_param("s", $_GET['q1']) === false) {
  die('binding parameters failed');
}
$stmt->execute() or die($con->error);
$stmt->bind_result($hs);
$stmt->fetch();
$stmt->close();
echo $hs;
?>

You are using $_GET . POST uses the variable $_POST .

If you want to use both, you can do:

$var = false;

if(isset($_GET['q1']))$var = $_GET['q1'];
else if(isset($_POST['q1']))$var = $_POST['q1'];

if($var===false) //trigger some error

And then use $var :

if ($stmt->bind_param("s", $var) === false) {
  die('binding parameters failed');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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