PHP - Does it need to fetch_array when select then insert - php

Hello I'm writing PHP and mysql. If I want to select then insert to database, I will
step1.Select from table
step2. mysqli_fetch_array and contain to variable such as $foo
step3. INSERT INTO MyTable (firstname)
VALUES ('$foo')"
Is it possible that I select then insert without fetch from database?

If you want to do this via mysql you can use
INSERT INTO Table2(field1, field2)
SELECT old_field1 as field1, old_field2 as field2 FROM Table1
Just be sure that you match fieldnames with "as".

Its a very simple concept,
mysqli_fetch_array()
returns an array and you cannot directly store an array into a column of a table in database. Either you have to map with the table column or convert it into json to store it into table column.

Related

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

How to get all last_insert_ids after running a single statement multiple insert query?

I have a 'location' table and a 'location_detail'[for inserting different language data] table. 'location_detail' contains FK of location table
I need to enter multiple location at a time. So what I am doing is:
run a 'for' loop inside that first I enter data into 'location' table get the loc_id then insert into location_detail table[Here in 'location_detail' table if more than one language present, again I want to run the query multiple times].
So if I want to add 3 locations -> Outer 'for' loop will run 3 times
total no of query exec. is 6 [If more than one language is present this will multiple]
==>My aim is to insert all 3(say) locations into 'location' table using multiple insert in a single statement and get all 3 last_insert_ids.
==>Next I can run single statement multiple insert query for adding into 'location_details' table
Here, how will I get this last_insert_ids in an array?
I'll do this in the same transaction/connection :
INSERT INTO location (col1, col2) VALUES (val1a, val2a);
SET #string_ids = LAST_INSERT_ID();
INSERT INTO location (col1, col2) VALUES (val1b, val2b);
SET #string_ids = CONCAT(#string_ids , ",", LAST_INSERT_ID());
INSERT INTO location (col1, col2) VALUES (val1c, val2c);
SET #string_ids = CONCAT(#string_ids , ",", LAST_INSERT_ID());
SELECT #string_ids ;
Then in php, I would explode this variable :
$array_ids = explode (",", $string_ids ).
Then build your request with php :
INSERT INTO location_detail(id, fk_id) VALUES
//foreach loop
(val_id1b, $array_ids[$i] )
(val_id2b, $array_ids[$i] )
(val_id3b, $array_ids[$i] )
I haven't tried the #array_ids but it should work.
Look at this link for more help if you need it.
I hope it fits your needs.
You can use transaction and get last_insert_id and calculate previous id's relate to your AUTO_INCREMENT settings.
Important
If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.
from Last Insert ID documentation.

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.

search and count values in column of mysql result set

I would like to search and count unique values in a column/fieldname of a MySQL Result Set.
In other words, when some lines of one table are stored in a mysql resultset I want to know which values are stored in a specific column/fieldname of all stored lines.
SELECT COUNT(DISTINCT columnname) AS Total FROM yourtable

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