mysql is it possible to do insert into insert? - php

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.

Related

Mysql Insert .... select, obtain last insert ID

I have this query in php. It's an insert select copying from table2, but I need to get the IDs of the newly created rows and store them into an array. Here is my code:
$sql = "INSERT INTO table1 SELECT distinct * from table2";
$db->query($sql);
I could revert the flow starting with a select on table2 and making all single inserts but it would slow down the script on a big table. Ideas?
You could lock the table, insert the rows, and get the ID of the last item inserted, and then unlock; that way you know that the IDs will be contiguous as no other concurrent user could have changed them. Locking and unlocking is something you want to use with caution though.
An alternative approach could be to use one of the columns in the table - either an 'updated' datetime column, or an insert-id column (for which you put in a value that will be the same across all of your rows.)
That way you can do a subsequent SELECT of the IDs back out of the database matching either the updated time or your chosen insert ID.

How to insert data while copy a column in mysql?

I want to insert data while copying a column.
$db->query("INSERT INTO transactions
(order_id,cart_id,full_name,email,phone,street1,street2,
city,state,zip_code,country,landmark,sub_total,tax,grand_total,
description,txn_type,paid,customer_id,items)
VALUES
('$order_id','$cart_id','$full_name','$email','$phone','$street1','$street2',
'$city','$state','$zip_code','$country','$landmark','$sub_total','$tax',
'$grand_total','$description','$txn_type','$paid','$customer_id', items
FROM cart WHERE id ='$cart_id')
");
In the above code, I am inserting all the values while copying
"items from cart where id=$cart_id".
what I am doing wrong?
seems you need an insert select
insert into transactions
(order_id,cart_id,full_name,email,phone,street1,street2,
city,state,zip_code,country,landmark,sub_total,tax,grand_total,
description,txn_type,paid,customer_id,items)
SELECT
'$order_id','$cart_id','$full_name','$email','$phone','$street1','$street2',
'$city','$state','$zip_code','$country','$landmark','$sub_total','$tax',
'$grand_total','$description','$txn_type','$paid','$customer_id', items
FROM cart WHERE id ='$cart_id'
bust you should not use php var in sql you are at risk for sqlinjection .. you should take a look at you mysql driver for prepared statements and binding param ..
You need to replace
VALUES(
with
( SELECT
Just refer INSERT ... SELECT Syntax

Writing INSERT query for multiple tables

I am writing a recipe database app and I have the database schema sorted but I am not struggling to figure out what query to write to insert the recipe into the database.
I have 3 tables
ingredients
ingredients_id...
recipes
recipe_id ...
recipes (pivot table)
ingredients_id
recipe_id
but it was my understanding that you can only insert data into one table at a time.
This is where my problem lies. If I have a form to input a recipe how do I add the recipe which is split over 3 tables? Do i use multiple queries. If so how can I guarantee they will match.
Sorry if this sounds like a dumb question but it is frying my brain, thanks in advance for the feedback.
Best regards
You guarantee the rows are related to one another by assigning common values to the appropriate columns.
If you have decided to define the recipe_id column in recipes to be AUTO_INCREMENT, and you insert a row which has a generated value assigned to that column, you can use the LAST_INSERT_ID() function to retrieve the value assigned to the column
INSERT INTO recipes (recipe_id, col2, col3) VALUES (NULL, 'fee', 'fi');
If the insert statement succeeded, you can retrieve the value assigned to recipe_id column (in the same MySQL session, before you execute any other statements), by executing a statement like this:
SELECT LAST_INSERT_ID() AS recipe_id;
NOTE: Some MySQL client libraries have methods/functions that perform this for you, so you can retrieve the value without having to prepare and execute another SQL statement in your code, e.g.
PDO::lastInsertId ref: http://www.php.net/manual/en/pdo.lastinsertid.php
mysqli::$insert_id ref: http://www.php.net/manual/en/mysqli.insert-id.php
You could then supply the value returned in the INSERT to the association table, for example
INSERT INTO recipe_ingredient (recipe_id, ... ) VALUES ( 42, ... )

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

SQL - INSERT and catch the id auto-increment value

What is the best way to get the auto-id value in the same SQL with a SELECT?
A forum said adding this "; has Return Scope_Identity()"
in the end of the SQL works in ASP.
Is there a corresponding way in PHP?
It depends on your database server. Using MySQL, call mysql_insert_id() immediately after your insert query. Using PostgreSQL, first query "select nextval(seq)" on the sequence and include the key in your insert query.
Querying for "select max(id) + 1 from tbl" could fail if another request inserts a record simultaneously.
In postgres the best way is to do something like:
insert into foos(name) values ('my_foo') returning id;
It depends on the database engine you are using. Some DBMS, like Firebird for example, have RETURNING clause you can add to your query. For example, if you have a table named TABLE1 with autoincrement column named ID, you can use this:
insert into TABLE1(columns...) values (values...) returning ID;
And it would return the inserted ID just like a regular select statement.
In Microsoft Transact SQL you can use ##IDENTITY.
e.g.
DECLARE #Table TABLE ( col0 INT IDENTITY, col1 VARCHAR(255), col2 VARCHAR(255))
INSERT INTO #Table (col1, col2) VALUES ('Hello','World!')
SELECT ##Identity
SELECT * FROM #Table
In php: mysql_insert_id()
http://us3.php.net/mysql_insert_id
or
If you wanted to genterate the number from your mySql select query, you could use this
EDIT:
SELECT LAST_INSERT_ID(`1`) + 1 FROM table
Be very careful: Apparently select nextval(seq) does not work in high concurrency - some other connection can insert between the time when you inserted and the time when you called select nextval(seq). Always test such code in high concurrency test harnesses.
In SQL Server a insert using the select statement can have an output clause which will return the identity value and whatever other columns you might need to identify which identity goes to which record. If you are using a values clause, then use select scope_identity () immediately after the insert.

Categories