如何创建MySQL触发器以跟踪更改

时间:2013-05-28 17:55:22

标签: php mysql triggers

我有一个名为“products”的表,以下列是此表中可以找到的示例(尽管还有更多):

  • products_id
  • our_cost

当price / our_cost更新时,我想在product_history表中插入一行,其中包含以下内容:

  • products_id正在更改
  • 字段被更改
  • 旧值
  • 新值
  • 进行更改的员工的员工ID(可用作PHP中的变量$ login_id)

这是我当前的触发器,虽然我希望这可以工作(除了输入employee_id)我收到错误Column count doesn't match value at row 1

DELIMITER |

CREATE TRIGGER after_update_products
    AFTER UPDATE ON products FOR EACH ROW
    BEGIN
        SET @History = '';

        IF NEW.price <> OLD.price THEN
            SET @History = CONCAT(@History, '(', OLD.products_id, ", price, ", OLD.price, ", ", NEW.price, "),");
        END IF;

        IF NEW.our_cost <> OLD.our_cost THEN
            SET @History = CONCAT(@History, '(', OLD.products_id, ", our_cost, ", OLD.our_cost, ", ", NEW.our_cost, "),");
        END IF;

        IF @History <> '' THEN
            SET @History = SUBSTRING(@History, 2, CHAR_LENGTH(@History) - 3);
            INSERT INTO products_history (products_id, field, old_value, new_value) VALUES (@History);
        END IF;
    END;
|

DELIMITER ;

我做错了什么?

最重要的是,我是否需要担心在我插入的内容周围加上引号(当我这样做时,上面的错误仍然存​​在),并且会逃避成为一个问题?

另外,如何让PHP将$ login_id添加到已更新的每一行?

3 个答案:

答案 0 :(得分:1)

尝试从@History周围删除'('和')'。

INSERT INTO products_history (products_id, field, old_value, new_value) VALUES @History;

此外,您将无法让PHP脚本将login_id传递给Trigger,因为这会超出PHP的影响。您可能无法使用TRIGGER,并且可能必须在PHP脚本中构建INSERT语句。

答案 1 :(得分:0)

为什么要创建额外的变量?你真的不需要它。你为什么不试试这个:

CREATE TRIGGER after_update_products
AFTER UPDATE ON products FOR EACH ROW
BEGIN
    IF NEW.price <> OLD.price THEN
        INSERT INTO products_history (products_id, field, old_value, new_value) VALUES (old.products_id,'price',old.price,new.price);
    END IF;

    IF NEW.our_cost <> OLD.our_cost THEN
        INSERT INTO products_history (products_id, field, old_value, new_value) VALUES (old.products_id,'our_cost',old.our_cost,new.our_cost);
    END IF;
END;

我不是很清楚你的上一个问题“另外,我怎样才能让PHP将$ login_id添加到已更新的每一行?”

答案 2 :(得分:0)

您可以简单地添加&#34; employee_id&#34;然后,触发器应该是这样的:

CREATE TRIGGER after_update_products
AFTER UPDATE ON products FOR EACH ROW
BEGIN
    IF NEW.price <> OLD.price THEN
        INSERT INTO products_history (products_id, field, old_value, new_value, guy, date) VALUES (old.products_id,'price',old.price,new.price,new.employe_id,now());
    END IF;

    IF NEW.our_cost <> OLD.our_cost THEN
        INSERT INTO products_history (products_id, field, old_value, new_value, guy, date) VALUES (old.products_id,'our_cost',old.our_cost,new.our_cost,new.employe_id,now());
    END IF;
END;