0

I'm trying to set up a button which when clicked adds a fixed number to the database value. The database is called var_stat and consists of id and value. The table has one row so far where id = var and value = 35. If clicked, the button should add 5 to the value making it 40.

I'm not sure what to do here, as all answers I found used a completely different approach and strings instead of integers. So far I have done this:

if (isset($_POST['n'])){
$n = $_POST['n'] ;
$stmt = $con->prepare('UPDATE var_stat SET value = value + $n WHERE id = ? ');
$stmt->bind_param('s', $id);
$id = "var";
$stmt->execute();
$stmt->close();
}
<script src="js/jQuery-3.4.1.js"></script>
  <script>
   function add(n){ 
    $.ajax({
        type: "POST",
        url: "update.php",
        data: {
            'n' : n
        },
        cache: false,
        success: function(response)
        {
        alert("Record successfully updated");
        }
    });
 }
  </script>
<form>
<input type="button" value="+5" class="btn btn-circle btn-grey col-sm-10" onclick="add(5);">
</form>

If I change $n in the update.php to an integer and run the update.php by itself it works, however I can't seem to get this to run through my html page, so I guess there's something wrong with my javascript code?

1 Answer 1

4

Bind the n as well, move the id before the binding statement

if (isset($_POST['n'])){
    $n = $_POST['n'] ;
    $id = "var";
    $stmt = $con->prepare('UPDATE var_stat SET value = value + ? WHERE id = ? ');
    $stmt->bind_param('is',$n, $id);
    $stmt->execute();
    $stmt->close();
}
Sign up to request clarification or add additional context in comments.

1 Comment

It seems like my comment didn't go through. It works like a charm, thank you very much for helping!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.