I've got a website that has personal messages and what I'm trying to do is when the person goes to the page to read a message it subtracts one from the amount of messages.
So in the table it has 3 columns - id, userID, and tally.
So for example, say for a user that tally is listed as 2, when they go to the page the code below is supposed to subtract to make it 1.
The problem I'm having is when it gets to 0 I don't want it to keep subtracting to where there's negative numbers.
I've been trying to use the code in this topic here - MySQL: update a field only if condition is met - but it's not working properly when I do it's giving me 500 errors or synax errors depending on what I try so I'm lost on what I'm doing wrong.
Original code (works but leaves the possibility for negative numbers).
<?php
$con=mysqli_connect("");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$userID=$_SESSION['user'];
// escape variables for security
$sql="update messagealert set userID='".$userID."', tally=tally - 1 where userID='".$userID."'";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "";
mysqli_close($con);
?>
Here's the updated statement as I have it:
$sql="update messagealert set userID='".$userID."', tally=tally - 1, WHEN tally>0 THEN tally-1
ELSE tally where userID='".$userID."'";