0

Im trying to build an easy textbased game in php to learn php. The problem is how do i UPDATE database table if certain parameters i met. 1 barracks cost 3000 and i want to check if the user got 3000 money or more. Only update then or say you need more money.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "phpsamples";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = UPDATE tbl_registered_users
SET     barracks = IF(money = '>3000', barracks + 1)
WHERE   id = 1";

if ($conn->query($sql) === TRUE) {
  echo "Record updated successfully";
} else {
  echo "Error updating record: " . $conn->error;
}

$conn->close();
?>
4
  • UPDATE ... SET barracks = barracks + (money > 3000), money = money - 3000 * (money > 3000) WHERE ... Commented Jul 2, 2020 at 7:33
  • Akinas set works, but you can do your code that way, you have to check it prior to update Commented Jul 2, 2020 at 7:38
  • @nbk no you don’t have to check upfront, you can also implement that check in the WHERE clause of the UPDATE statement. Commented Jul 2, 2020 at 8:23
  • he wants to decline the update, if the money isn't enough, that happoens if money is smaller than 300 no baracks is increased, but the update commands will not give an error so if ($conn->query($sql) === TRUE) will not be triggert Commented Jul 2, 2020 at 9:02

2 Answers 2

1
UPDATE table SET
   money = money - 3000,
   barracks = barracks + 1
WHERE id=1 
  AND money>= 3000

This will upp the barracks and reduce the money for user id=1 ONLY if he has 3000 or more money.

To check if the update applied (i.e. if the user indeed has the money) you can use mysqli_affected_rows(), which

Returns the number of rows affected by the last INSERT, UPDATE,REPLACE or DELETE query.

If it returns 0 there was no update because the WHERE clause wasn't met, so you can send the 'not enough money' message.

If it returns 1 the WHERE clause was met and the user has one more barracks.

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

1 Comment

@RonvanderHeijden You're right, but I assume that if the user doesn't exist he can't login at all so he'll never come to the point of buying something.
0

It is better to fetch the specific user by user id. Then check the parameters and update.

$query = $conn->query("select * from tbl_registered_users where id = 1");
if ($query->num_rows > 0) {
    $row = $query->fetch_assoc();
    if($row["money"] > 3000) {
       $conn->query("update tbl_registered_users set barracks = barracks + 1 where id = 1");
    }
}

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.