Subtract or add database value with submitted value

Subtract or add database value with submitted value

TronikTronik Posts: 122Questions: 28Answers: 1

I want to increase or decrease a value that exists in the database.

The sql syntax would be

UPDATE products SET stock_alter = stock_alter + $value

This is what I have in server side script

if ( isset( $_POST['action'] ) && $_POST['action'] === 'edit' ) {
  $db->push( 'products', [ 'stock_alter' => 'stock_alter' + $_POST['data'][key($_POST['data'])]['addstock'] ],  [ 'id' => key($_POST['data']) ]);
}

Was not sure if it would work, but it did not. Removing the "'stock_alter' +" part works as far as setting the value, but thats not what I want.

Maybe there is another way of acheiving what I want?

I do not want it done on client side.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    Our SQL libraries aren't really designed with that sort of operation in mind. Instead, use the $db->raw() method - e.g.:

    $db
      ->raw()
      ->bind(':after', $_POST['data'][key($_POST['data'])]['addstock'] ])
      ->exec('UPDATE products SET stock_alter = stock_alter + :after');
    

    Docs for that method are here.

    Allan

  • TronikTronik Posts: 122Questions: 28Answers: 1

    Perfect, thanks a lot!

This discussion has been closed.