0

I'm trying to make a function work, where I ask for a number of free seats left in a car, and if executed, it subtracts 1 from the result and updates the cell in database.

Sql statements must be correct... am I missing out on anything else?

function seatCalc($id){

    $stmt=$this->connection->prepare("SELECT seats_left FROM drive WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->bind_result($seat_count);
    $stmt->execute();

    return $seat_count;

    if($seat_count >= 1){

        $seat_count -= 1;

        $stmt=$this->connection->prepare("UPDATE drive SET seats_left=? WHERE id=?");
        $stmt->bind_param("ii", $seat_count, $id);
        $stmt->execute();
    }

}

It's a part of my university project and unfortunately, I can't reach my professor at the moment.

Thank you in advance!

3
  • if($seat_count>0) ? Commented Dec 15, 2014 at 20:27
  • Uuh, a horrible typo here, ($seat_count >= 1) or ($seat_count > 0) both do not give any result, corrected wrong comparison here Commented Dec 15, 2014 at 20:29
  • the function never makes it to your if statement.. Commented Dec 15, 2014 at 20:30

3 Answers 3

4

Your return statement breaks you out of the function before the if block gets processed.

Sign up to request clarification or add additional context in comments.

Comments

0
  • your condition is incorrect;
  • you have unreached statements after return;

Here is code:

function seatCalc($id){
  $stmt=$this->connection->prepare("SELECT seats_left FROM drive WHERE id=?");
  $stmt->bind_param("i", $id);
  $stmt->bind_result($seat_count);
  $stmt->execute();
  if($seat_count > 0){
    $stmt=$this->connection->prepare("UPDATE drive SET seats_left=seats_left-1 WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
  }
  return $seat_count;
}

Also you can substract one with database..

2 Comments

$seat_count > 0 is the same as $seat_count >= 1
Yess, I dont know why I couldn't think of subtracting one with database directly.. Thank you sir!
0

Oh boy

function seatCalc($id){

    $stmt=$this->connection->prepare("SELECT seats_left FROM drive WHERE id=:i");
    $stmt->bind_param(":i", $id);
    $stmt->execute();

    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $seat_count = intval($row['seats_left']);

    if($seat_count > 0){

        $seat_count -= 1;

        $stmt=$this->connection->prepare("UPDATE drive SET seats_left=seats_left-1 WHERE id=:id");
        $stmt->bind_param(":id", $id);
        $stmt->execute();
    }
    return $seat_count;
}

Comments

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.