create a trigger for getting client ip address into column in MySQL

2.8k Views Asked by At
CREATE TABLE `project` (
  `prj_id` int(11) NOT NULL AUTO_INCREMENT,
  `prj_name` varchar(400) NOT NULL,
  `prj_customer_id` int(11) NOT NULL,
  `prj_url` varchar(400) NOT NULL,
  `prj_description` varchar(400) NOT NULL,
  `prj_status` int(11) NOT NULL,
  `prj_member_id` int(11) NOT NULL,
  `prj_crtd_by` varchar(50) NOT NULL,
  `prj_crtd_dt` datetime NOT NULL,
  `prj_updt_by` varchar(50) NOT NULL,
  `prj_updt_dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `prj_last_ip` varchar(50) NOT NULL,
  PRIMARY KEY (`prj_id`),
  KEY `fk_project_customer_customer_id` (`prj_customer_id`),
  KEY `fk_project_member_member_id` (`prj_member_id`),
  CONSTRAINT `fk_project_customer_customer_id` FOREIGN KEY (`prj_customer_id`) REFERENCES `customer` (`cus_id`),
  CONSTRAINT `fk_project_member_member_id` FOREIGN KEY (`prj_member_id`) REFERENCES `member` (`mem_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I want to create trigger for three columns for this table project. I want to create trigger for columns of prj_crtd_dt, which insert the date when it is created, prj_updt_dt which insert the date when it is updated, prj_last_ip which has to update the ip address of the system from where it is created.

I have created trigger for the date column and I want to know how to create for ip address CREATE TRIGGER create_date_of_customer BEFORE INSERT ON customer FOR EACH ROW SET NEW.cus_crtd_dt = NOW(); NEW.cus_updt_dt = NOW();

1

There are 1 best solutions below

3
On

Your question is not illustrated. However according to my understanding the follwing will help you. Have you seen https://msdn.microsoft.com/en-us/library/ms189799.aspx?

EDITED

This for your edited question.For getting the IPAddress you have to enable the cmdshell. However, Enabling xp_cmdshell has security drawbacks and I won't advise you on doing so. If you can use servername instead of server IP then try this,

SET NEW.cus_crtd_dt = NOW();
    NEW.cus_updt_dt = NOW();
    NEW.cus_last_ip= SERVERPROPERTY('MachineName');

or this,

SET NEW.cus_crtd_dt = NOW();
    NEW.cus_updt_dt = NOW();
    NEW.cus_last_ip= @@SERVERNAME;