multiple Insert in sp - php

I have these tables in a MYSQL database:
tBook (idBook,BookName)
tAuthor (idAuthor,AuthorName)
tBookAuthor (FK_Book,FK_Author)
I want to insert in one stored procedure a new book. In the same procedure I want to insert into the table tBookAuthor.
INSERT INTO `tBook`
(`idBook`, `BookName`)
VALUES
(23, 'myBookName')
INSERT INTO `tBookAuthor`
(`FK_Book`, `FK_Author`)
VALUES
(LAST_INSERT_ID(), 526)

The problem was that I tried to modify a storec procedure which already exists.
I did this in PHPmyAdmin.
If you want to create a new stored procedure you do it like this:
DELIMITER //
CREATE PROCEDURE new_person(
first CHAR(35), last CHAR(35), email CHAR(255), tool_id INT)
BEGIN
START TRANSACTION;
INSERT INTO `tBook`
(`idBook`,
`BookName`)
VALUES
(23
'myBookName')
INSERT INTO `tBookAuthor`
(`FK_Book`,
`FK_Author`)
VALUES
(LAST_INSERT_ID(),
526)
COMMIT;
END//
DELIMITER;
If you want to ALTER a stored procedure in phpmyadmin you do it like this:
BEGIN
START TRANSACTION;
INSERT INTO `tBook`
(`idBook`,
`BookName`)
VALUES
(23
'myBookName')
INSERT INTO `tBookAuthor`
(`FK_Book`,
`FK_Author`)
VALUES
(LAST_INSERT_ID(),
526)
COMMIT;
END

Instead of a stored procedure, since you are using PHP, I suggest doing 2 inserts, since the second insert is foreign keys you'll have to select the author, get the last insert ID of the book and do a simple insert there.
It's a lot less trouble.
I also have some trouble understanding your dB structure, can one book be written by more than one author? If so, my bad, otherwise, save yourself the trouble of the helper table and just put the author id on the book.

Related

Mysql auto insert on new table

Can anyone explain me what below code actually do, I have this on my mysqlDB.sql exported file
DROP TRIGGER IF EXISTS `alertupdateevent`;
DELIMITER $$
CREATE TRIGGER `alertupdateevent` AFTER INSERT ON `RECOG`
FOR EACH ROW BEGIN
INSERT INTO `mydb`.`ALERTUPDATES` (`FIRSTNAME`, `LASTNAME`, `CAMNAME`, `TIMESTAMP`, `RESERVE1`, `ALERTTYPE`, `IMGURL`) VALUES (NEW.FIRSTNAME, NEW.LASTNAME, NEW.DOB, NEW.TIMESTAMP, NEW.FACEID, 'RECOG' , NEW.FACEURL);
END
$$
DELIMITER ;
Currently I dealing a project which is not developed by me, and I am not well familiarized with mysql.
The problem I am facing is I have two table in DB like RECOG and ALERTUPDATES and I need to insert data to both of these table(same data), and I can see only one php which insert data to the table `RECOG'.
So my question does the above piece of code insert data automatically to table ALERTUPDATES when data insert on RECOG table by php.
Yes, you are correct.
Trigger are used to INSERT UPDATE on some TABLE based on action perform on some TABLE actions like insert, update or delete.
Refer MySQL triggers
Try this..
CREATE TRIGGER trigger_name
BEFORE INSERT
ON table_name FOR EACH ROW
BEGIN
-- variable declarations
-- trigger code
END;
Parameters or Arguments
trigger_name
The name of the trigger to create.
BEFORE INSERT
It indicates that the trigger will fire before the INSERT operation is executed.
table_name
The name of the table that the trigger is created on.
RESTRICTIONS
You can not create a BEFORE trigger on a view.
You can update the NEW values.
You can not update the OLD values.
Example:
DELIMITER //
CREATE TRIGGER contacts_before_insert
BEFORE INSERT
ON contacts FOR EACH ROW
BEGIN
DECLARE vUser varchar(50);
-- Find username of person performing INSERT into table
SELECT USER() INTO vUser;
-- Update create_date field to current system date
SET NEW.created_date = SYSDATE();
-- Update created_by field to the username of the person performing the INSERT
SET NEW.created_by = vUser;
END; //
DELIMITER ;
Ref:http://www.techonthenet.com/mysql/triggers/before_insert.php

Is it possible to insert data in two different table using single mysql query without transaction?

I know this is possible using transaction but I want to do it using single mysql query.
this is which common format transaction
START TRANSACTION;
SELECT #A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=#A WHERE type=1;
COMMIT;
but I need to know a single mysql query is possible?
Normally, you can not do this in MySQL. But you can do this using concat query.
INSERT INTO your_table
(value1,value2,value3)
VALUES
(a,b,c),
(d,e,f),
(i,j,k);
But this is not your question answer. so Your question answer is NO. MYSQL is not support it still now.
No, it can't be done in single statement like
insert into table1,table2
either you do separately like
insert into table1 ...
insert into table2 ...
(OR)
Wrap the insert statements in stored procedure and call that procedure like
create procedure sp_insert_multiple
as
begin
insert into table1 ...
insert into table2 ...
end
Call the SP
exec sp_insert_multiple
You can't do this. However, you can use a transaction and have both of them be contained within one transaction.
START TRANSACTION;
INSERT INTO table_1 VALUES ('1','2','3');
INSERT INTO table_2 VALUES ('one','two','three');
COMMIT;
See the following rule
Normally it is not possible to insert multiple table in single query. you can insert multiple row in a single table . like as
INSERT INTO tbl_test
(a1,a2,a3)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
you can do this in Oracle
by using procedure you can insert
create procedure insert_query
as
begin
insert into tbl_test1(a1,a2,a3) VALUES (1,2,3)
insert into tbl_test2 (b1,b2,b3) VALUES (1,2,3)
end
you can do that like coz
MySQL doesn't support multi-table insertion in a single INSERT statement.
INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)
here is a link of detail answer..
sql - insert into multiple tables in one query

mysql is it possible to do insert into insert?

what am doing is clonning an old database to new one with different structure but should have same old data
is it possible to do an insert into insert that return id of the insert query
INSERT INTO tab1 (nom,id_2) VALUES
("jack",(INSERT INTO tab2 (pass) VALUES ("1234")));
in INSERT INTO tab2 (pass) VALUES ("1234") i want to get the id of the insert
but no luck!! (i want it in one sql query (i already know about mysql_insert_id) )
thanks in advance
You cant do this on a single query - use mysql_insert_id() to get the last inserted id for example :
mysql_query('INSERT INTO tab2 (pass) VALUES ("1234")');
$lastid = mysql_insert_id();
mysql_query('INSERT INTO tab1 (nom,id_2) VALUES ("jack",'.$lastid.')');
insert id can be retrieved in mysql as well, so here is a version with no PHP involved (it however performs 2 queries)
INSERT INTO tab2 (pass) VALUES ("1234");
INSERT INTO tab1 (nom,id_2) VALUES("jack",LAST_INSERT_ID());
Lock the table, insert, select max(id), unlock table. This is the only way outside creating your own sequence tables like in postgres if you are adverse for some reason to the last insert id functions. This approach however is going to be like pouring tar into a blender if your table is moderate to high writes.
You can't do this as a single insert because inserts are atomic that is, the ID isn't determined until the statement completes.
Wrap both statements in a transaction and you will get your ID, and atomicity.

How to Update if the data exist else insert the new data (multiple rows)

I need to create a insert and update statement, when today date is not in the database it will insert else it will update the QTY (from excel [this part I have done]) get from today.
But, there have a lots of row need to be insert and update.
1) it will check for the last 4 days in database, if there doesn't include today, it will just insert the data for today and update the last 3 days data. in the other hand, if there contain today it will just update.
P.S: I had try to use INSERT... ON DUPLICATE KEY UPDATE but it only 1 row affected.
If else statement , when i used this it only insert one row of data then the rest it just doing update.
Can give me some advise or example.
suppose you bulk copy your data from excel to a temporary table tbl and your actual table is tbl1 then do something like this
begin transaction;
if not exists(select * from tbl(updlock holdlock) where...)
begin
insert into tbl1...
else
begin
update tbl1...
end
commit;
What language are you using to do this? I have done something similar in Ruby before. I would make the column (Date in your case) unique at the database level then simply try inserting each record. When I get an exception thrown because the Date is not unique I would then proceed to update the QTY.
I found this article on mysql which says it supports multiple insert.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);
That statement is identical to the following two statements:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=3;
INSERT INTO table (a,b,c) VALUES (4,5,6)
ON DUPLICATE KEY UPDATE c=9;
So if we want to edit straight, we could do something like this.
INSERT INTO table (uniquekey,data) VALUES (1,2),(4,5)
ON DUPLICATE KEY UPDATE data=VALUES(data);

How do I check if data exists in my SQL table and if it doesn't insert the newer data?

My table is made up of 3 values-
long
short
id
id is an auto increment int value and the rest are text.
My PHP script retrieves the latest version of a program every half an hour and stores it as long in an sql table. What I want is for the php script to check if the value is already in the table(i.e. there are no new versions). If it isn't I want it to insert the new data.
Just to make this clear I am not replacing the value "long". I am merely making a new value of it and 'id' is keeping a record of how many versions there have been.
Use the EXISTS Keyword.
INSERT INTO Table (Col1, Col2, Col3)
Values(?, ?, ?)
WHERE NOT EXISTS (
SELECT Col1 FROM TABLE
WHERE Col1 = ? AND Col2 = ? AND Col3 =?)
You can work out which columns you actually need to test.
You can put a UNIQUE index on the long column and use INSERT IGNORE:
INSERT IGNORE INTO versions (long, short)
VALUES (?, ?)
If the key already exists MySQL will generate a warning (not an error) and will neither insert nor update any rows.

Categories