I'm trying to make this work:
$articles_id = 105; // comes from argument
$type = 'units_out'; // comes from argument
$quantity = 4; // comes from argument
$date = date('Y-m-d');
$sql = "INSERT INTO stock (articles_id, date, units_in, units_out)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE $type = IF(VALUES($type) - $quantity >= 0, VALUES($type) - $quantity, 0)";
$res = $this->db->query($sql, array($articles_id, $date, 0, $quantity));
The record already exists, so it does an update. The initial value of units_out in BD is 2, and its an UNSIGNED MEDIUMINT field. So, since it's unsigned type, 2 - 4 = -2, which for an UNSIGNED MEDIUMINT means start counting down from its max value.
After the query, units_out=16777215. I want to avoid this behaviour by using the VALUES() function of MySQL, but it isn't working if I use it with bd->query()
I've tried by directly doing it in PHPMyAdmin and it does work, units_out results in 0. Why this isn't working in Codeigniter?