Trigger Error with MySQL - mysql

I'm doing something simple. Basically everytime a user register themself into the system, a trigger should run and copy the row which contain the ID and insert it into another table called userinfo.
Theres two table. One only contain username id and password, and another one contains foreign key linking the users.UserID and userinfo.UserID. I wish to insert new user to userinfo everytime users table is updated with new member. However the trigger keeps giving me error. Can someone tell me what am I doing wrong?
I'm open for any easier/proper way too. This is my first time playing with trigger.
CREATE TRIGGER NewUsers_Trigger AFTER insert ON users FOR EACH ROW
BEGIN INSERT INTO `pms`.`userinfo` (`UserID`, `FirstName`, `LastName`,
`Address`, `City`, `Country`, `PostCode`, `PhoneNumber`) VALUES ('2',
'test', 'test', 'test', 'test', 'test', 'test', 'test'); END

Trigger needs delimiter to be set, also you mentioned that there is a foreign key so the trigger should look like
delimiter //
CREATE TRIGGER NewUsers_Trigger AFTER insert ON users
FOR EACH ROW
BEGIN
INSERT INTO `pms`.`userinfo` (`UserID`, `FirstName`, `LastName`,
`Address`, `City`, `Country`, `PostCode`, `PhoneNumber`) VALUES (new.UserID,
'test', 'test', 'test', 'test', 'test', 'test', 'test');
END; //
delimiter ;
Note I have removed 2 with new.UserID which is the last inserted id from the user table so that same id is inserted to the other table and there is no error raised on foreign key constraints

Related

error when insert new values into database in infinityfree

When i use InfinityFree hosting, my register form doesn't work. But in localhost it's no problem.
I am trying to insert into my phpmyadmin database. The first column is the user_id column an it's an auto_increment field.
if i do this :
INSERT INTO `user` (`user_id`, `email`, `username`, `password`, `game_id`) VALUES('', '$email', '$username', '$password', '$game_id')
the error is :
Incorrect integer value: '' for column 'user_id' at row 1
and if i do this :
INSERT INTO `user` (`user_id`, `email`, `username`, `password`, `game_id`) VALUES(NULL, '$email', '$username', '$password', '$game_id')
the error is :
Data truncated for column 'game_id' at row 1
Instead of assigning a NULL value to user_id, just leave the user_id out of the query.
It should be like this:
INSERT INTO user (email, username, password, game_id) VALUES('$email', '$username', '$password', '$game_id')

MySQL triggers - I've set them up to populate a new table but need a way to populate from existing data

Title says most of it - I've setup a new table that's populated by other tables via triggers.
Obviously that new table has no data yet - I need to find a way to get it populated with the existing data rather than just new stuff as it comes in.
Triggers are update/create/delete so I could update a field somewhere to add a space at the end then remove it, but that seems a little...weird
Any ideas please? I've searched on here and can't see one.
example would be table posts, insert trigger then populates table posts_stats with a count(*)
It's specifically to trigger the triggers from existing data.
Thanks!
I suggest Create View.
Reason:
MySQL supports views, including updatable views. Views are stored queries that when invoked produce a result set. A view acts as a virtual table. (Mysql Manual)
I will Explaination based on case:
Create table:
CREATE TABLE `sample_user` (
`id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(16) DEFAULT NULL,
`gender` enum('F','M') DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=ascii
Insert Sample Data:
insert into `sample_user` (`id`, `name`, `gender`) values('1','Aalona','F');
insert into `sample_user` (`id`, `name`, `gender`) values('2','Abbie','F');
insert into `sample_user` (`id`, `name`, `gender`) values('3','Brielle','F');
insert into `sample_user` (`id`, `name`, `gender`) values('4','Abigail','F');
insert into `sample_user` (`id`, `name`, `gender`) values('5','Caleb','M');
insert into `sample_user` (`id`, `name`, `gender`) values('6','Damian','M');
Sample Data:
Syntax Create View:
CREATE VIEW sample_view
AS SELECT gender,COUNT(*) total FROM `sample_user` GROUP BY gender
In Sqlyogeditor will look like this:
After that you can select from that view.
SELECT * FROM sample_view
Result:
Further Read:
https://dev.mysql.com/doc/refman/8.0/en/views.html

Creating a table and Inserting values in db browser (sqlite)

I am new at scripting and am trying to create a table and insert values into the table below using DB Browser (SQLite).
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS "Doctor" (
"Doctorid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
"DoctorName" TEXT NOT NULL,
"DoctorSpecialty" TEXT NOT NULL,
"ConsultationFee" NUMERIC NOT NULL
);
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(2,'Rose','Cardiology',375),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(3,'Johnson','Neurology',250),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(4,'Leath','Pharmacy',400),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(5,'Anderson','Anesthesiology',500),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(6,'Copeland','Radiology',550),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(7,'Macklin','Orthopedic Surgeon',575),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(8,'Witherspoon','Immunizations',100),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(9,'Pope','Billing',50),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(10,'Cockfield','Pediatrics',100);
COMMIT;
Once I run the script, I receive an error:
Result: near "INSERT": syntax error
At line 7:
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300),
INSERT
Line 7 is: );
Im not sure what im doing wrong, can someone please help. Thanks.
remove Doctorid at insert time because it is AUTOINCREMENT.
INSERT INTO Doctor
(DoctorName,DoctorSpecialty,ConsultationFee) VALUES
('Wells','Respiritory Therapy',300);
and put the semicolon (;) end of the query
Inserting multiple values should be like this. You don't need to repeat INSERT statement.
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300),
(2,'Rose','Cardiology',375),
(3,'Johnson','Neurology',250),
(4,'Leath','Pharmacy',400);
or change the comma to semi colon in each INSERT statement.
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300);
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(2,'Rose','Cardiology',375);

SQL - Insert into table if doesn't have data

I'm using MYSQL script and I want to insert some values in a table.
INSERT INTO `testType` (`name`) VALUES ('URL');
INSERT INTO `testType` (`name`) VALUES ('xD');
INSERT INTO `testType` (`name`) VALUES ('LOL');
But I only want to insert if the table is empty in the first place.
I'm not a SQL guy but basically
if(testType.length() == 0 {
INSERT INTO `testType` (`name`) VALUES ('URL');
INSERT INTO `testType` (`name`) VALUES ('xD');
INSERT INTO `testType` (`name`) VALUES ('LOL');
}
How can I do this the simplest and smallest way possible? Thank you.
EDIT: my question is different. I want to insert ALL THE DATA if the table is empty. not only one insert at the time
First, I would suggest doing this in one step:
INSERT INTO testType(name)
VALUES ('URL'), ('xD'), ('LOL');
Then, you can express this without IF:
INSERT INTO testType(name)
SELECT t.name
FROM (SELECT 'URL' as name UNION ALL
SELECT 'xD' as name UNION ALL
SELECT 'LOL' as name
) t
WHERE NOT EXISTS (SELECT 1 FROM testType);
Finally, if you want to insert these values if each doesn't exist, then you can let the database do the work. First, define a unique constraint/index on the name (if name is not already the primary key), and then use ON DUPLICATE KEY UPDATE:
CREATE UNIQUE INDEX unq_testtable_name ON testtable(name);
INSERT INTO testType(name)
VALUES ('URL'), ('xD'), ('LOL')
ON DUPLICATE KEY UPDATE name = VALUES(name);
You can use stored procedure
DELIMITER //
CREATE PROCEDURE `proc1` ()
BEGIN
SELECT COUNT(*) INTO variable1 FROM testType;
IF variable1 = 0 THEN
INSERT INTO `testType` (`name`) VALUES ('URL');
INSERT INTO `testType` (`name`) VALUES ('xD');
INSERT INTO `testType` (`name`) VALUES ('LOL');
END WHILE;
END //
Try this:
DECLARE #ExistCount INT;
SET #ExistCount = (SELECT COUNT(1) FROM `testType`);
IF #ExistCount<1
THEN
INSERT INTO `testType` (`name`) VALUES ('URL'),('xD'),('LOL');
END IF;

MySQL SHA256 with Insert Statement

I want to create a script to fill a database for testing. How would I set a string to be hashed and the inserted into the database?
I have:
INSERT INTO `loop`.`User`
(`userID`,
`firstName`,
`lastName`,
`email`,
`password`,
`userName`,
`bio`,
`spamCount`)
VALUES
('gZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL',
'Joe',
'Smith',
'test0#email.com',
SHA2('testgZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL', 256),
'test0#email.com',
"TEST BIO",
0);
How do I hash the string and INSERT in same statement?
You can insert a SELECT instead of VALUES to run a function on one of the inputs:
INSERT INTO `loop`.`User`
(`userID`,
`firstName`,
`lastName`,
`email`,
`password`,
`userName`,
`bio`,
`spamCount`)
SELECT
'gZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL',
'Joe',
'Smith',
'test0#email.com',
SHA2('testgZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL', 256),
'test0#email.com',
"TEST BIO",
0;
If you already have the table filled by some content, you can alter it with the following :
ALTER TABLE `page` ADD COLUMN `hash` char(64) AS (SHA2(`content`, 256)) AFTER `content`
This solution will add hash column right after the content one, generates hash for existing and new records too without need to change your INSERT statement.