0

am struggling with what seems should be a simple, thing. Namely to update database entry for a user with a variable. Here is the code am using:

function UpdateDB(username){
alert(username);
//username="John";
    $.ajax({
    async: false,
    dataType: 'json',
        type: "POST",
        url: "file.php",
        data: {'username':username},
       });
}

function is called onlick, and username is defined as :var username=document.getElementById("username").innerHTML;. Both are defined before function is called and should not cause any problems. Alert gives correct var value. Associated bit in external PHP file (file.php) is:

if(isset($_POST['username'])){

    $username=$_POST['username'];
    $query = "UPDATE users SET Country='USA' WHERE username='$username'";


    if(mysqli_query($db, $query)){
        echo "Records were updated successfully.";
    } else {
        echo "ERROR: Could not able to execute $query. " . mysqli_error($db);
    }   
}

However, Country entry does not get updated for a var username in the database. However it works fine if instead of using variable, i just uncomment //username="John";. What am i doing wrong? Thank you.

  • 1
    could you provide the output of var_dump($query); in php please just to check what exact query get's executed there. – Daniel Resch Aug 17 '21 at 11:23
  • 1
    In your browser's debugging tools, what is the response from the AJAX request? In that AJAX request is the expected `username` value present? As an aside, you should never use `async: false` in your AJAX requests. It's actively being deprecated and is just a bad idea in general. Additionally, your server-side code is *wide open* to [**SQL injection**](https://stackoverflow.com/q/60174/328193). – David Aug 17 '21 at 11:24
  • 1
    Your question shows you are not aware of the dangers of SQL injection. Please take the time to look into PDO and use that instead of mysqli. Here is a tutorial: https://phpdelusions.net/pdo. – Alexander van Oostenrijk Aug 17 '21 at 11:27
  • Thanks Everyone. I have actually managed to resolve that myself. And I appreciate your comments on using async: false and sql injection, which I havent even heard of before. – luca amarelli Sep 20 '21 at 19:18

0 Answers0