I have 3 tables:
customer
email
phone
Everyone of them with its own AUTO_INCREMENT id (id_customer, id_email, id_phone) and I have 2 more tables to relate them:
customer_email
customer_phone
These tables contain the others's tables ids as foreign keys.
How can I relate them in a single SQL statement using LAST_INSERT_ID()? Or what do you recommend?
You can store the results of LAST_INSERT_ID() using variables.
INSERT INTO email(...) VALUES (...);
SET #email_id = LAST_INSERT_ID();
INSERT INTO phone(...) VALUES (...);
SET #phone_id = LAST_INSERT_ID();
INSERT INTO customer_phone(id_email, id_phone) VALUES(#email_id, #phone_id);
Related
I have a little problem. I've create a two tables 'kontrola' and 'naruszenie'. In kontrola table I have a foreign key relation to 'naruszenie' table. When I want to display all records belong to 'kontrola' table I use this:
$listakontroli = $connecting->query("SELECT k.id, k.podmiot, k.miasto, k.wszczeto, k.zakonczono, n.naruszenie FROM kontrola k INNER JOIN naruszenia n ON k.naruszenie_id=n.id");
And everything working properly.
How to create a query INSERT TO to add the new record using this 2 tables?
EDIT:
Now I have query like this but doesn't work
$dodajKontrole = "INSERT INTO kontrola (podmiot, miasto, wszczeto, zakonczono, naruszenie_id) VALUES ('$nowyPodmiot', '$noweMiasto', '$datawszczecia', '$datazakonczenia', '$nowenaruszenie')";
Try to use a mysql TRIGGER if you want to do it in mySQL level
CREATE TRIGGER insert_into_naruszenia AFTER INSERT ON `kontrola`
FOR EACH ROW
BEGIN
INSERT INTO naruszenia (naruszenie) VALUES (NEW.id)
END;
INSERT INTO kontrola (....) VALUES (....);
I didn't test it but is should do the job.
If you want to use it inside php code you always have the LAST_INSERT_ID() that you can use.
INSERT INTO kontrola (....) VALUES (....);
INSERT INTO naruszenie (id) VALUES (LAST_INSERT_ID());
i need to insert some data into the table 'companies' with columns :
company_id | company_name
and at the same time (from the same form) into another table 'contact_persons' :
contact_name | company_id
where the company_id must be the value from 'companies' table where company_id is a PK and AI.
Is it possible to do that in ONE single step instead of inserting first the company_name and then reading the table 'companies' and retrieving the 'company_id' to insert it into the second table ('contact_persons')?
I'm not sure if that is possible, but it would be much more elegant and efficient...
Thanks in advance.
You can do it using LAST_INSERT_ID() to get the last auto increment id from Companies table and inserting the same in other table. something like
INSERT INTO companies (company_name) VALUES ('test');
SET #last_id_companies = LAST_INSERT_ID();
INSERT INTO contact_persons (contact_name, company_id)
VALUES ('test', #last_id_companies);
Not in a single statement, but in a single transaction, so they are both executed at the same time and rolled back.
START TRANSACTION;
--Your statements here
COMMIT;
I have a query like
Insert into tbl(str)values('a'),('b'),('c')
if i had a single insert then by using mysqli_insert_id($con) i could get last id inserted but how get all ids inserted in this multiple insert query?
This behavior of last_insert_id() is documented in the MySQL docs:
The currently executing statement does not affect the value of
LAST_INSERT_ID(). Suppose that you generate an AUTO_INCREMENT value
with one statement, and then refer to LAST_INSERT_ID() in a
multiple-row INSERT statement that inserts rows into a table with its
own AUTO_INCREMENT column. The value of LAST_INSERT_ID() will remain
stable in the second statement; its value for the second and later
rows is not affected by the earlier row insertions. (However, if you
mix references to LAST_INSERT_ID() and LAST_INSERT_ID(expr), the
effect is undefined.)
IF you really need it you can test it using foreach with array_push
<?php
$InsetQueryArray = array(
"Insert into tbl(str) values('a')",
"Insert into tbl(str) values ('b')",
"Insert into tbl(str) values('c')"
);
$allLasIncrementIds = array();
foreach ($InsetQueryArray as $value) {
//execute it mysql
//Then use array_push
array_push($allLastIncrementIds, mysqli_insert_id($con));
}
?>
If it is just for a few rows, you could switch to sending individual inserts with last_insert_id(). Otherwise it will slow down your application notably. You could make a marker for those bulk inserts, which gets set to a number identifying this bulk insert at the bulk insert itself and you can fetch those ids later on:
insert into tbl (stuff, tmp_marker) values ("hi",1715),("ho",1715),("hu",1715);
select group_concat(id) from tbl where tmp_marker = 1715;
update tbl set tmp_marker=0 where tmp_marker=1715;
If those bulk inserts have a meaning, you could also make a table import_tbl with user and time and filename or whatever and keep the 1715 as reference to that import.
EDIT: After discussion, I would go to an import-table
CREATE TABLE import (id int(11) not null auto_increment primary key, user_id int(11), tmstmp timestamp);
When an import starts, insert that:
INSERT INTO import set user_id = $userId;
in php:
$importId = last_insert_id();
$stmt = "insert into tbl (str, import_id) values ('a',$import_id), ('b', $import_id),('c',$importId);
Then you can do whatever you want with the id of your recently imported rows.
I have not made research if a multi-row-insert is guaranteed to lead to a consecutive row of IDs, as in a combination of last_insert_id() and num_rows is presupposed. And if that stays so, even when MySQL increases parallelization. So I would see it as dangerous to depend on it.
I have problems with the last line of the code:
if(isset($_POST['kolona']))
{
foreach($_POST['kolona'] as $vrednost)
mysql_query("ALTER TABLE tablica ADD $vrednost text NOT NULL");
mysql_query("INSERT INTO tablica ( ".(implode(',',($_POST['kolona']))).") SELECT ".(implode(',',($_POST['kolona'])))." FROM druga");
}
First query is making columns in table 'tablica' and second query suppose to insert values in that columns from all tables from which are the columns, for now it's just hard coded, it's only from table 'druga', but i don't know how to go through the all tables, not just 'druga'. I tried with a loop and also with implode function but nothing seems to be working. Can anyone help?
You can tackle merging problems like this using the ON DUPLICATE KEY feature:
INSERT INTO target (id, column1, column2)
SELECT id, column1, column2 FROM source
ON DUPLICATE KEY UPDATE column1=VALUES(column1), column2=VALUES(column2)
It works well provided you have a PRIMARY KEY column without conflicts between your source and target tables.
So, I was wondering if you were to launch this query:
INSERT INTO users (name, gender, location) VALUES ('Ricky-Bobby', 'm', 'Daytona Beach, FL');
And suppose that users has another auto-incrementing columns for the primary key, how would you be able to get the value of that primary key without launching another query?
Codeigniter simplifies the MySQL query SELECT LAST_INSERT_ID() through the function $this->db->insert_id().
Although this is a query, it's a very light one that won't be a performance issue. One thing to have in note is this:
If you want the ID on the row you inserted; $this->db->insert_id()
If you want the auto_increment value, that is the next value that an INSERT will have as id, simply $this->db->insert_id() + 1
codeigniter makes this available with $this->db->last_insert_id()
http://ellislab.com/codeigniter/user-guide/database/helpers.html
You can combine LAST_INSERT_ID() with your query:
INSERT INTO users (name, gender, location) VALUES ('Ricky-Bobby', 'm', 'Daytona Beach, FL');
SELECT LAST_INSERT_ID();
You could use this if you are using PDO
http://php.net/manual/en/pdo.lastinsertid.php