简体   繁体   中英

Updating Mysql database data using Php and Ajax

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?

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();
}

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