B. Rain
B. Rain

Reputation: 135

Incrementing variable by 1 changes variable value to 1 in php

As the title states, I seem to be having an issue with incrementing a variable in my .php file code, it modifies the value in the database, acc_points, to 1 after I increment acc_points by one in the variable above. What the code does is send an ajax request to the php which then updates the data in the mysql database and then returns the data to the js and the js will then alert the data.

The incrementation somehow changes the value of acc_points from 5 to 1. I also considered if the problem had something to do with sessions. I've looked around for relevant information but couldn't find a solution. Would like to find out the real cause of this issue. Thanks!

Here are the codes:

.php file

<?php

    require 'dbcon.php';

    session_start();

    $acc_points = $_SESSION["acc_points"];
    $acc_id = $_SESSION["acc_id"];

    if(isset($acc_points))
    {
      $acc_points++;
    }

    $result = $con->prepare(" UPDATE `points` SET `acc_points` = ?  WHERE `acc_id` = ? ");
    $result->bind_param("ii", $acc_points, $acc_id);
    $result->execute();

    if($acc_points != null)
      {
          $response = $acc_points;
          echo $_GET['callback'] . '(' . json_encode($response) . ')';
      }
      else
      {
          $response = "'Failed. Please try again.'";
          echo $_GET['callback'] . '(' . json_encode($response) . ')';
      }  
        //connection closed
        mysqli_close ($con);

    ?>

js file

$(document).ready(function() {

    $("#qrtest").click(function() {

        {
            $.ajax({
                    type: "GET",
                    url: "http://127.0.0.1/MP/appqrcode.php?callback=?",
                    dataType: 'JSONP',
                    async: false,
                    jsonp : "callback",
                    jsonpCallback: "jsonpcallback",

                    success: function jsonpcallback(response) 
                    {

                        alert(response.acc_points);

                    }
            })
        }
    });
});

Upvotes: 2

Views: 58

Answers (1)

e4c5
e4c5

Reputation: 53774

The first problem is that you are checking the value of $acc_points in the code below, but you are executing the query regardless of whether it's null or not null

if(isset($acc_points))
{
     $acc_points++;
} // if condition ends here. Insert command will always be executed.

Then after the comand has been executed you check the value again

if($acc_points != null)  /// insert has already happend.
{
}

So you should restructure your code, but better still, you don't need this approach at all. Why not just?

 $result = $con->prepare(" UPDATE `points` SET `acc_points` = acc_points+1  WHERE `acc_id` = ? ");

This increments the value already in the database.

Upvotes: 2

Related Questions