Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Syed1980's avatar

Is this the correct way to write trigger for my table in MySql?

DELIMITER $$

  CREATE TRIGGER before_insert_part_compatibility
  BEFORE INSERT ON part_compatibility
  FOR EACH ROW
  BEGIN
-- Step 1: Remove backslashes and extra quotes
SET NEW.model_id = REPLACE(REPLACE(NEW.model_id, '\\', ''), '\"', '"');

-- Step 2: Ensure model_id is a valid JSON string
SET NEW.model_id = JSON_QUOTE(REPLACE(REPLACE(NEW.model_id, '[', ''), ']', ''));

-- Step 3: Optional Logging for Debugging
INSERT INTO debug_log (log_message, created_at)
VALUES (CONCAT('Cleaned model_id: ', NEW.model_id), NOW());

END$$

 DELIMITER ;
0 likes
2 replies
jlrdw's avatar

I am no expert on triggers. But here is one I used in the past that worked.

DELIMITER $$

USE `pbackdate`$$

DROP TRIGGER /*!50032 IF EXISTS */ `trzero_tonull`$$

CREATE
    /*!50017 DEFINER = 'root'@'localhost' */
    TRIGGER `trzero_tonull` BEFORE INSERT ON `pets` 
    FOR EACH ROW BEGIN
IF NEW.ownerid = 0 THEN
    SET NEW.ownerid = NULL;
END IF;
END;
$$

DELIMITER ;

But test yours in development to see if it works ok or not.

A good source: https://www.mysqltutorial.org/mysql-triggers/

Please or to participate in this conversation.