Yvo van Oosterum
Yvo van Oosterum

Reputation: 43

PHP incrementing a var

I am building a car parking application in which different users have different numbers of parking spots. This number is set by an administrator in a database. The user can input a numberplate which then will be added to a database as well. What I want is that when a user has occupied all the spots, that he will not be able to insert any more number plates.

However, now I have the following code at the moment:

if(isset($_POST['number_plate'])){
  $numberPlate = $_POST['number_plate'];
  $user_id = $_SESSION['id'];

  $query = mysql_query("SELECT `parking_spots` FROM `login` WHERE `id` = ".$user_id." ");
  $row = mysql_fetch_assoc($query);
  $totalNumberOfSpots = $row['parking_spots'];  
  $occupiedNumberOfSpots = 0;

  $sql = "INSERT INTO amsterdam (numberplate, user_id) VALUES ('$numberPlate','$user_id')";
  if(mysql_query($sql))
  { 
    echo 'numberplate added';
    $occupiedNumberOfSpots++;

    if($occupiedNumberOfSpots == $totalNumberOfSpots) 
    {
        echo "There are no more spots avialable";
    }
  }
  else 
  { 
    echo 'Something went wrong!';
  }
}

But when I echo the $occupiedNumberOfSpots variable it keeps returning 1 and does not increment every time I add numberplate.

How can I solve this issue?

Upvotes: 0

Views: 86

Answers (1)

malutki5200
malutki5200

Reputation: 1112

It is because You are running the same code each time You add a plate to your db.

this:

$occupiedNumberOfSpots = 0;

should be taken from db as well. I guess it should be like that:

$totalNumberOfSpots = 100; // for example 
$occupiedNumberOfSpots = $row['parking_spots']; // taken from db

instead of:

$totalNumberOfSpots = $row['parking_spots'];  
$occupiedNumberOfSpots = 0;

Upvotes: 1

Related Questions