Question

I am trying to update a value in a MySQL database with the following function which creates an update statement that subtracts the value of the $seats variable from the existing value in the places field in the database. The code below returns 0 instead of reducing the places value by the value of the $seats variable.

    $update_seats = update_places($id);

    function update_places($id) {
         global $modx;
         $table = "`database_name`.`table_name`";
         $update_seats = '`places`' - $seats;
         $result = $modx->db->update( '`places` = ' . $update_seats, $table, '`id` = "' . $id . '" AND `places` > 0' );
         return $result;         // Returns 'true' on success, 'false' on failure.

}

Any help with correcting my syntax is greatly appreciated.

Was it helpful?

Solution

$seats variable is undefined inside function, you need to use:

function update_places($id, $seats)

and then call it $update_seats = update_places($id, 123);

also, change your query to be more correct:

$result = $modx->db->update( '`places` = ' . $update_seats, $table, '`id` = ' . intval($id, 10) . ' AND `places` >= ' . $seats );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top