Search code examples
phpsqldelete-row

Decrement a database table value if value >= 1 else... Delete the record


I want to decrement a database table value if the field value is greater than or equal to 1 (>= 1). Otherwise (if it IS less than 1) then I want to delete that whole database record, My code decrements the value continuously but does not delete the record when it reaches less than 1.

I think the $Check variable does not hold the Quantity field value but I'm not sure:

Using MySQL

Here is my code:

$Check = "SELECT Quantity FROM Cart WHERE ItemCode = '1'";

if($Check >= '1')
{
    $Query = "UPDATE Cart SET Quantity = Quantity - 1 WHERE ItemCode = '1'";
    mysql_query($Query);
}
else
{
    $DeleteRow = "DELETE FROM Cart WHERE ItemCode = '1'";   
    mysql_query($DeleteRow);
}

mysql_close();

Solution

  • Try this piece of code:

    <?php
    
        $Check = "SELECT Quantity FROM Cart WHERE ItemCode = '1'";
        $result = mysql_query($Check);
    
        $row = mysql_fetch_assoc($result);
        if($row['Quantity'] >= '1'){
        $Query = "UPDATE Cart SET Quantity = ".$row['Quantity']." - 1 WHERE ItemCode = '1'";
    
        mysql_query($Query);
    
        }
        else
        {
        $DeleteRow = "DELETE FROM Cart WHERE ItemCode = '1'";
        mysql_query($DeleteRow);
        }
    
        mysql_close();
    

    ?>

    When you have this code running ok, try to adapting it to the mysqli extension on the procedural way; the mysql extension is deprecated.

    It's not recommended the use of the mysql extension; you should try mysqli or PDO instead, follow this link and made your choice: http://www.phptherightway.com/#databases