Triggers does cannot be created in phpMyAdmin - php

following is a trigger which I created in MySQL Workbench and the related tables are below as well. the trigger works perfectly in workbench but when I try to created the same trigger in phpMyAdmin, it gives me the follow error
Error
There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem
ERROR: Unknown Punctuation String # 11
STR: //
SQL: delimiter //
CREATE TRIGGER log_user_delete
BEFORE DELETE ON user
FOR EACH ROW
BEGIN
INSERT INTO log_user(user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on,
modified_from) SELECT user_id, first_name, last_name, contact_no,
user_type, email, password, active, modified_by, modified_on,
modified_from FROM user WHERE OLD.user_id = user_id;
SQL query: Documentation
delimiter // CREATE TRIGGER log_user_delete BEFORE DELETE ON user FOR EACH ROW BEGIN INSERT INTO log_user(user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from) SELECT user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from FROM user WHERE OLD.user_id = user_id;
MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'delimiter //
CREATE TRIGGER log_user_delete
BEFORE DELETE ON user
FOR EACH ROW' at line 1.
what am I doing wrong?
2 tables :-
CREATE TABLE user (
user_id INT(11) NOT NULL AUTO_INCREMENT,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
contact_no VARCHAR(25) NOT NULL,
user_type VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
active INT(1) NOT NULL,
modified_by INT(11) NOT NULL,
modified_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
modified_from VARCHAR(20) NOT NULL,
PRIMARY KEY (user_id)
);
CREATE TABLE log_user (
log_id INT(11) NOT NULL AUTO_INCREMENT,
user_id INT(11) NOT NULL,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
contact_no VARCHAR(25) NOT NULL,
user_type VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
active INT(1) NOT NULL,
modified_by INT(11) NOT NULL,
modified_on DATETIME,
modified_from VARCHAR(20) NOT NULL,
log_modified_by INT(11) NOT NULL,
log_modified_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
log_modified_from VARCHAR(20) NOT NULL,
status VARCHAR(10) NOT NULL,
PRIMARY KEY (log_id)
);
Trigger :
DELIMITER //
CREATE TRIGGER log_user_delete
BEFORE DELETE ON user
FOR EACH ROW
BEGIN
INSERT INTO log_user(user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from) SELECT user_id, first_name, last_name, contact_no, user_type, email, password, active, modified_by, modified_on, modified_from FROM user WHERE OLD.user_id = user_id;
UPDATE log_user SET status = 'DELETED' WHERE log_id = last_insert_id();
END;
// DELIMITER ;

Related

MySQL Insert with skipping duplicate values

I am new to MySQL. I am getting a user phonebook from their mobile device, and I am saving into a database.
Table Phonebook (User ID is INT)
INSERT INTO `Phonebook`
(`user_id`, `first_name`, `mobile`)
VALUES(4,'tom','+919810012345');
It works fine, but if user again upload his phonebook then I want to skip users existing contacts and add only new one from his/her phonebook and the data can be compare with user_id, first_name, mobile and these columns can't be duplicate.
If the user has +919810012345 and the next time 9810012345/9810-0123-45 then add again to the database.
I tried this, but it's not working:
INSERT Phonebook (`user_id`, `first_name`, `mobile`)
Values (SELECT `user_id`, `first_name`, `mobile`
FROM Phonebook
where `user_id` != $user_id
AND `first_name` !=$name
AND `mobile` != $phn)
Table Schema
CREATE TABLE `Phonebook` (
`id` int NOT NULL AUTO_INCREMENT,
`user_id` int NOT NULL,
`first_name` varchar(250) NOT NULL,
`mobile` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3520 DEFAULT CHARSET=latin1
Phone Book Table
Table Name: PhoneBook
id user_id first_name mobile
1 100 John +91981000000
2 100 Tom 91981000001
3 100 Ron 9810-000-02
4 100 Mat 91981000003
5 100 Miley 981000004
Add a UNIQUE constraint
CREATE TABLE `Phonebook` (
`id` int NOT NULL AUTO_INCREMENT,
`user_id` int NOT NULL,
`first_name` varchar(250) NOT NULL,
`mobile` varchar(250) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE (`user_id`, `first_name`, `mobile`)
) ENGINE=InnoDB AUTO_INCREMENT=3520 DEFAULT CHARSET=latin1
INSERT INTO `Phonebook`
(`user_id`, `first_name`, `mobile`)
VALUES(4,'tom','+919810012345');
SELECT * FROM `Phonebook`
id
user_id
first_name
mobile
3520
4
tom
+919810012345
INSERT INTO `Phonebook`
(`user_id`, `first_name`, `mobile`)
VALUES(4,'tom','+919810012345')
ON DUPLICATE KEY UPDATE user_id = user_id;
SELECT * FROM `Phonebook`
id
user_id
first_name
mobile
3520
4
tom
+919810012345
fiddle

INSERT INTO table2 SELECT FROM table1 then UPDATE table1 rows that selected/inserted

I am writing a procedure to copy data from a table data_entry to another table promotional
Table structure of data_entry is as below (excluded non-related fields ) -
CREATE TABLE `data_entry` (
`school_id` int(11) NOT NULL AUTO_INCREMENT,
`school_name` varchar(255) NOT NULL,
`mobile_number` varchar(15) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`website` varchar(255) DEFAULT NULL,
`city` varchar(250) DEFAULT NULL,
`pin` varchar(6) DEFAULT NULL,
`is_copied_to_promo` tinyint(4) DEFAULT '0'
PRIMARY KEY (`school_id`)
)
Table structure of promotional (excluded non-related fields )
CREATE TABLE `promotional` (
`promo_id` int(11) NOT NULL AUTO_INCREMENT, //renamed to avoid confusion
`school_name` varchar(255) NOT NULL,
`mobile_number` varchar(15) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`website` varchar(255) DEFAULT NULL,
`city` varchar(250) DEFAULT NULL,
`pin` varchar(6) DEFAULT NULL,
`copied_school_id` INT, // edit - school_id of data_entry table will go here
PRIMARY KEY (`promo_id`)
)
Here is the procedure to copy all rows from data_entry to promotional where is_copied_to_promo=0.
Procedure
CREATE PROCEDURE `uspCopySchoolsToPromotional`(IN param_insert_datetime DATETIME)
BEGIN
INSERT IGNORE INTO promotional (
school_name,
mobile_number,
email,
website,
city,
pin,
copied_school_id
)
SELECT school_name,
mobile_number,
email,
website,
city,
pin,
school_id
FROM data_entry
WHERE is_copied_to_promo =0 ;
END;
What I want to do now to update is_copied_to_promo to 1 in data_entry table for all the inserted/affected rows from above procedure so that each time I execute above procedure only new rows from data_entry table should copy to promotional.
I am calling this procedure via PHP code. The solution can be adding update query in the same procedure or run another query/procedue after executing uspCopySchoolsToPromotional.
Thanks in advance.
EDIT :
I forgot to mention that school_id in both tables are different. In promotional table data is coming from multiple sources. So I renamed the school_id with promo_id in promotional table to avoid your confusion.
If you copied over the school_id as well then you have a unique key to work with, and you could then add an UPDATE after the INSERT to do this, like:
CREATE PROCEDURE `uspCopySchoolsToPromotional`(IN param_insert_datetime DATETIME)
BEGIN
INSERT IGNORE INTO promotional (
school_id,
school_name,
mobile_number,
email,
website,
city,
pin
)
SELECT school_id,
school_name,
mobile_number,
email,
website,
city,
pin,
FROM data_entry
WHERE is_copied_to_promo =0 ;
UPDATE data_entry
SET is_copied_to_promo=1
WHERE
school_id=(SELECT school_id FROM promotional)
AND is_copies_to_promo=0;
END;
Hope this helps :)
Mysql 8 was supposed to have Common Table Expressions but it doesn't seem to appear in the release announcements, so you will have to use some other mechanism to implement this. One solution is to use an after insert trigger
CREATE TRIGGER data_entry AFTER INSERT ON promotional_update
FOR EACH ROW
BEGIN
UPDATE data_entry SET
WHERE is_copied_to_promo = 1 WHERE school_id = new.ID;
END
Another solution is to take a table level lock and update after the insert
CREATE PROCEDURE `uspCopySchoolsToPromotional`(IN param_insert_datetime DATETIME)
BEGIN
LOCK TABLES data_entry WRITE;
....
UPDATE data_entry
SET is_copied_to_promo=1
WHERE
school_id=(SELECT school_id FROM promotional)
AND is_copies_to_promo=0;
UNLOCK TABLES:
END;
Note that if you don't lock tables, you may find that race conditions result in inconsistencies. The two methods (trigger vs lock and update) have their pros and cons.
You can follow Flauntster's query if you do not have School_id as auto_increment in both the tables.
if the column is auto_increment in both the tables, then you can follow below query
CREATE PROCEDURE `uspCopySchoolsToPromotional`(IN param_insert_datetime DATETIME)
BEGIN
INSERT IGNORE INTO promotional (
school_id,
school_name,
mobile_number,
email,
website,
city,
pin
)
SELECT school_id,
school_name,
mobile_number,
email,
website,
city,
pin,
FROM data_entry
WHERE is_copied_to_promo =0 ;
UPDATE data_entry de
JOIN promotional p ON de.school_name = p.school_name
AND de.mobile_number = p.mobile_number
AND is_copies_to_promo = 0
SET is_copied_to_promo=1;
END;
Hope this should solve your problem.

Make new users automatically follow a user

I am working on a php site with uses mysql as database, now my site is a social network like site where users follow each other, now if a user joins in he is following nobody so his stream remains empty so they leave the site quickly as well,i want users to be following my account account automatically when he joins in. Can you please tell me how to do it
here are the two tables
Table structure for table sn_users
CREATE TABLE IF NOT EXISTS `sn_users` (
`id` int(11) NOT NULL,
`username` varchar(225) NOT NULL,
`email` varchar(225) NOT NULL,
`password` varchar(225) NOT NULL,
`name` varchar(225) DEFAULT NULL,
`picture` varchar(100) NOT NULL,
`cover` varchar(100) DEFAULT NULL,
`job` varchar(225) DEFAULT NULL,
`address` varchar(225) DEFAULT NULL,
`date` int(11) NOT NULL,
`reg_id` text,
`active` int(11) NOT NULL DEFAULT '1'
) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
Table structure for table sn_follows
CREATE TABLE IF NOT EXISTS `sn_follows` (
`id` int(11) NOT NULL,
`from` int(11) NOT NULL,
`to` int(11) NOT NULL,
`date` int(11) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=74 DEFAULT CHARSET=utf8;
Run the query when the user get registerd.
<?
//Register query
$con = mysqli_connect("[HOST", "[USER]", "[PASS]", "[DB]");
$query1 = "INSERT INTO sn_users
(username, email, password, name, picture, cover, job, address, date, reg_id, active)
VALUES
('$username', '$email', '$password', '$name', '$picture', '$cover', '$job', '$address', 'date', 'reg_id', 'active')";
mysqli_query($con, $query);
//Auto follow query
$query2 = "INSERT INTO sn_follows
(`id`, `from`, `to`, `date`)
VALUES
([ID], '[NEW REGISTERD ACCOUNT], '[YOUR ACCOUNT]', '[DATE]')";
mysqli_query($con, $query2);
Hints:
Make of the field id in your database an auto_increment
Make sure you put a hashed password in the database
you need to do some modifications in your script.
1) get last inserted id of new registered user
2) insert that last id in sn_follows table with your id
this may elaborate flow
after your user register insert query get last id like below
example:
$sql = "INSERT INTO sn_users (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$sqlfloow = "insert into sn_follows (from,to,date) values("your id",$last_id,date("Y-m-d H:i:s"))";
}

Why isn't my INSERT IGNORE code NOT working?

I am trying to avoid inserting duplicates records into my table by using the PRIMARY KEY and INSERT IGNORE methods. As suggested # http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm
I added the PRIMARY KEY to the tables definition as shown below:
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("flightSched") or die(mysql_error());
mysql_query("CREATE TABLE Alteration(
id INT NOT NULL AUTO_INCREMENT,
timePeriod TIME default '00:00:00',
depOrArriv VARCHAR(9),
flightNo VARCHAR(9) NOT NULL,
airline VARCHAR(20),
dest VARCHAR(30),
origin VARCHAR(30),
depature VARCHAR(8),
don VARCHAR(10),
arrivalTime VARCHAR(8),
arrivalTimeSec VARCHAR(28),
status VARCHAR(15) NOT NULL,
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_name varchar(50) not null default '',
PRIMARY KEY (id, flightNo, status)
)")
or die(mysql_error());
echo "Table Created!";
Find below the INSERT IGNORE code:
mysql_query("INSERT IGNORE INTO Alteration
(depOrArriv, flightNo, airline, origin, don, arrivalTime, arrivalTimeSec, status, image_type, image, image_size, image_name)
VALUES('$depOrArriv', '$flightNo', '$airline', '$origin', '$don', '$arrivalTime', '$arrivalTime', '$status', '$image_type','$image', '$image_size', '$image_name' ) ");
// or die(mysql_error());
echo "Number of affected rows were: " . mysql_affected_rows();
While testing it I noticed that it STILL inserts duplicate records.
Why is it still doing this? Can anyone help me point out what is wrong?
Any help is greatly appreciated.
Looking forward to your feedback.
Your id column is auto incrementing which means each row is effectively unique when it is used in your key. You should inspect the data that you've inserted. You should see that each duplicate row actually has a separate and distinct id.
You can set a UNIQUE index on flightNo and status which would prevent the duplicate rows.
ALTER TABLE `Alteration` ADD UNIQUE (
`flightNo` ,
`status`
);
And then I would recommend just reducing your Primary Key to be id
UPDATE
As requested, this is a modified version of your code with a unique index used to prevent the duplicates:
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("flightSched") or die(mysql_error());
mysql_query("CREATE TABLE Alteration(
id INT NOT NULL AUTO_INCREMENT,
timePeriod TIME default '00:00:00',
depOrArriv VARCHAR(9),
flightNo VARCHAR(9) NOT NULL,
airline VARCHAR(20),
dest VARCHAR(30),
origin VARCHAR(30),
depature VARCHAR(8),
don VARCHAR(10),
arrivalTime VARCHAR(8),
arrivalTimeSec VARCHAR(28),
status VARCHAR(15) NOT NULL,
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_name varchar(50) not null default '',
PRIMARY KEY (id),
UNIQUE KEY `flightNo` (`flightNo`,`status`)
)") or die(mysql_error());
echo "Table Created!";
mysql_query("INSERT IGNORE INTO Alteration (depOrArriv, flightNo, airline, origin, don, arrivalTime, arrivalTimeSec, status, image_type, image, image_size, image_name) VALUES('$depOrArriv', '$flightNo', '$airline', '$origin', '$don', '$arrivalTime', '$arrivalTime', '$status', '$image_type','$image', '$image_size', '$image_name' )");
echo "Number of affected rows were: " . mysql_affected_rows();

Cannot insert into table - Foreign key constraint issue in mysql

I have two tables main_jobs and sub_jobs with the structures below:
$query="create table if not exists main_jobs (
id int not null auto_increment, primary key(id),
industry int(3),
company_name varchar(255),
job_title varchar(255),
email varchar(255),
website varchar(255),
introduction text not null,
application_details text,
advert_date date,
expiry_date date,
upload_date date,
no_deadline int(1) default 0,
logo varchar(255),
featured varchar(20),
source varchar(10) default 'admin',
email_status int default 0,
views int(11) default 1,
short_url varchar(100),
tags varchar(255),
FOREIGN KEY (industry) REFERENCES industry (id))";
if(mysql_query($query,$link)){echo "main_jobs created<br>";} else{ die(mysql_error()); }
$query="create table if not exists sub_jobs (
id int not null auto_increment, primary key(id),
parent_id int(11) not null, FOREIGN KEY (parent_id) REFERENCES main_jobs (id),
title varchar(255),
description text not null,
category int (3), FOREIGN KEY (category) REFERENCES category (id),
job_type varchar(20),
job_level varchar(50),
min_qualification varchar(50),
min_experience int(3),
max_experience int(3),
min_salary int(11),
max_salary int(11),
show_salary int(1) default 1,
denomination varchar(10),
views int(11) default 1,
short_url varchar(100),
email varchar(255),
website varchar(255))";
if(mysql_query($query,$link)){echo "sub_jobs created<br>";} else{ die(mysql_error()); }
I want to insert records but it shows up this error:
Cannot add or update a child row: a foreign key constraint fails (`myjobmag_db`.`sub_jobs`, CONSTRAINT `sub_jobs_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `main_jobs` (`id`))
These are mysql queries and have been staring at them for hours but cannot identify the problem:
Insert into main_jobs (Runs successfully)
$resultobj=otherquery("insert into main_jobs(industry, company_name, job_title, email, website, introduction, application_details, advert_date, expiry_date, upload_date, no_deadline, logo) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "ssssssssssss", array($industry, $company_name, $job_name, $email, $website, $profile, $application, $advert_date, $expiry_date, $date_uploaded, $no_deadline, $logo));
I pick the id of the last insert (confirms that it exists in main_jobs table, this is do manually because of the error) and run insert into sub_jobs
$parent= $resultobj['obj']->insert_id;
mysql_query("insert into sub_jobs(id, parent_id, title, description, category, job_type, job_level, min_qualification, min_experience, max_experience, min_salary, max_salary, show_salary, denomination, email, website) values('', $parent, '$subtitle', '$description', '$category', '$type', '$level', '$min_qualification', '$min_experience', '$max_experience', '$min_salary', '$max_salary', '$show_salary', '$denomination', '$sub_email', '$sub_website')", $link) or die(mysql_error($link));
In my last test the id in main_jobs table is 2616 and it actually exists, yet i get an error.
Kindly assist!

Categories