Skip to content

Instantly share code, notes, and snippets.

@simofacc
Last active March 13, 2016 00:28
Show Gist options
  • Save simofacc/061aaf189a559a0817bf to your computer and use it in GitHub Desktop.
Save simofacc/061aaf189a559a0817bf to your computer and use it in GitHub Desktop.
MySQL trigger to generate a slug before inserting a new row
CREATE DEFINER=`[USER_NAME]`@`%` TRIGGER `[DATABASE_NAME]`.`Slug` BEFORE INSERT ON `[TABLE_NAME]`.`games` FOR EACH ROW
BEGIN
IF NEW.slug IS NULL THEN
SET NEW.slug = LOWER(TRIM(NEW.name));
SET NEW.slug = REPLACE(NEW.slug, ':', '');
SET NEW.slug = REPLACE(NEW.slug, ')', '');
SET NEW.slug = REPLACE(NEW.slug, '(', '');
SET NEW.slug = REPLACE(NEW.slug, ',', '');
SET NEW.slug = REPLACE(NEW.slug, '\\', '');
SET NEW.slug = REPLACE(NEW.slug, '?', '');
SET NEW.slug = REPLACE(NEW.slug, '\'', '');
SET NEW.slug = REPLACE(NEW.slug, '&', '');
SET NEW.slug = REPLACE(NEW.slug, '!', '');
SET NEW.slug = REPLACE(NEW.slug, '.', '');
SET NEW.slug = REPLACE(NEW.slug, '€', '');
SET NEW.slug = REPLACE(NEW.slug, 'euro;', '');
SET NEW.slug = REPLACE(NEW.slug, ' ', '-');
SET NEW.slug = REPLACE(NEW.slug, '--', '-');
END IF;
END;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment