Fix that SQL-injection
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$sql = "INSERT INTO table1 VALUES ('username','password');
// You must quote your $vars ^ ^ ^ ^ like this
// or syntax errors will occur and the escaping will not work!.
Note that storing unencrypted passwords in a database is a cardinal sin.
See below on how to fix that.
Triggers do not allow parameters
You can only access the values you just inserted into the table.
The Insert trigger has a dummy table new
for this.
The Delete triger has a dummy table old
to see the values that are to be deleted.
The Update trigger has both old
and new
.
Other than that you cannot access any outside data.
DELIMITER $$
//Creates trigger to insert into table1 ( logs ) the userid and patientid ( which has to come from php )
CREATE
TRIGGER ai_table1_each AFTER INSERT ON `baemer_emr`.`table1`
FOR EACH ROW
BEGIN
INSERT INTO table2 VALUES (NEW.idn, NEW.username, NEW.patientid);
END$$
The solution
Create a blackhole table.
Blackhole tables to not store anything, their only reason to exist is for replication purposes and so you can attach triggers to them.
CREATE TABLE bh_newusers (
username varchar(255) not null,
password varchar(255) not null,
idn integer not null,
patient_id integer not null,
user_id integer not null) ENGINE = BLACKHOLE;
Next insert data into the blackhole table and process that using a trigger.
CREATE
TRIGGER ai_bh_newuser_each AFTER INSERT ON `baemer_emr`.bh_newuser
FOR EACH ROW
BEGIN
DECLARE newsalt INTEGER;
SET newsalt = FLOOR(RAND()*999999);
INSERT INTO users (username, salt, passhash)
VALUES (NEW.username, newsalt, SHA2(CONCAT(newsalt, password), 512));
INSERT INTO table2 VALUES (NEW.idn, NEW.username, NEW.patient_id);
END$$
Notes on the trigger
You should never store passwords in the clear in a database.
Always store them as a salted hash using the safest hash function (currently SHA2 with a 512 key length) , as shown in the trigger.
You can test to see if someone has the correct password by doing:
SELECT * FROM user
WHERE username = '$username' AND passhash = SHA2(CONCAT(salt,'$password'),512)
Links
http://dev.mysql.com/doc/refman/5.0/en/blackhole-storage-engine.html
http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html
Storing hashed passwords in MySQL
How does the SQL injection from the "Bobby Tables" XKCD comic work?