Question

I am trying to update a MySQL database field (decrease the value by 1) in a specific row (ID) of the "places" column, as long as the number in the field is greater than 0.

(see the example statement below)

UPDATE table SET places = places - 1 WHERE id = $id AND places > 0

The statement below fails apart from changing the value of the field to zero. I would be grateful if anyone can help with the syntax error.

if($id){
    global $modx;
    $table = "`database_name`.`table_name`";
    $update_seats = "`places` - 1";
    $result = $modx->db->update( '`places` = "' . $update_seats . '"', $table, '`id` = "' . $id . '" AND `places` > 0' );
    return $result;         // Returns 'true' on success, 'false' on failure.
    }
Was it helpful?

Solution

You have enclosed new value of field in double quotes

$result = $modx->db->update( '`places` = "' . $update_seats . '"', $table, '`id` = "' . $id . '" AND `places` > 0' );

what is evaluated as string in MySQL query. Remove double quotes here

'`places` = "' . $update_seats . '"'

so that it looks like this

$result = $modx->db->update( '`places` = ' . $update_seats, $table, '`id` = "' . $id . '" AND `places` > 0' );

OTHER TIPS

The query looks ok, if you need to set minimum value of 1 to places you should simply change the query accordingly:

UPDATE table SET places = places - 1 WHERE id = $id AND places > 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top