Daniel Vítek
Daniel Vítek

Reputation: 185

MySQL trigger take text variable

Let's say we got two tables.

First table is items - id, title.
Second table is history - id, title, action, user.

We can have following AFTER INSERT trigger for "This user inserted this item":

INSERT INTO history (title, action, user) VALUES (NEW.title, 'INSERT', @phpUserId);

If I want to insert new item, I can do something like this.

SET @phpUserId = 123;
INSERT INTO items (title) VALUES ('My best item');

In this case, trigger works perfectly.

But the problem is, when I add some text into variable - for example SET @phpUserId = "library123"; - In this moment the trigger is not able to take that variable.

Any ideas why only integer variables are passed?

Upvotes: 0

Views: 475

Answers (1)

P.Salmon
P.Salmon

Reputation: 17640

Good news there's nothing wrong with your trigger and here's the proof

drop table if exists i,h;
create table i(id int, title varchar(20));
create table h(id int, title varchar(20), action varchar(20), user varchar(30));

drop trigger if exists t;
delimiter $$
create trigger t after insert on i
for each row 
begin
    INSERT INTO h (title, action, user) VALUES (NEW.title, 'INSERT', @phpUserId);
end $$

delimiter ;

SET @phpUserId = 123;
INSERT INTO i (title) VALUES ('My best item');
SET @phpUserId = 'bob123';
INSERT INTO i (title) VALUES ('My worst item');

+------+---------------+--------+--------+
| id   | title         | action | user   |
+------+---------------+--------+--------+
| NULL | My best item  | INSERT | 123    |
| NULL | My worst item | INSERT | bob123 |
+------+---------------+--------+--------+
2 rows in set (0.00 sec)

Upvotes: 1

Related Questions