mysql insert into two tables id from first - php

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;

Related

php Mysqli - i want to change id number of some rows to end id

my table has an id field with auto_increment and I want some rows to move to end of the table (changing number id to end number).
Like This:
$query= mysqli_query($con,"UPDATE moshakhasat SET id=<?end table?> WHERE username='$username' ");
sorry about this code. I don't know a lot about PHP
I am tired and really need your help
Thank you.
I'm not sur if you can change that as mysql is handling the auto increment.
But maybe you could insert new row with your data and then delete the old row.
you could use the INSERT... SELECT syntax
INSERT INTO tbl1 (field1, field2, ...)
SELECT tbl1.field1, tbl1.field2
FROM tbl1 WHERE id IN (1,2,3,4);
then
DELETE FROM tbl1 WHERE id IN (1,2,3,4)

Inserting Columns Without Duplicated Null Data in MySQL?

i don't know mysql very much. And i've problem about that. I've a database and it's 20 GB. I want to combine 4 columns and then move the combined column to the new one. But the problem is duplicated data in the table.
For example i wanna combine;
Column1(Not Null),
Column2(Some of them null, some of them not null),
Column3(Not Null),
Column4(Some of them null, some of them not null).
And my new column, which i want to move my combined columns, is fully empty. After my longly research, at last i find this code on dev.mysql.com
INSERT INTO my_table (new_content)
SELECT Column1
FROM my_table WHERE my_table > 0;
As a result, it moved Column1 to the new_content. But my the other 20 columns were duplicated too, as empty fields. How can i make it in an easy way?
Sorry for my bad English. Thanks in advance.
If you want a resulting column based on the string concatenation fo the column you can use concat
INSERT INTO my_table (new_content)
SELECT concat(Column1 , Column2, Column3, Column4)
FROM my_table ;
Create the column in already existing table:
ALTER TABLE my_table ADD COLUMN new_content VARCHAR(55);
Update table and concate all the columns to the newly created column:
UPDATE my_table SET new_content = CONCAT(Column1, Column2);
Create a trigger for all inserting values in future as well:
CREATE TRIGGER insert_trigger
BEFORE INSERT ON my_table
FOR EACH ROW
SET new.new_content = CONCAT(Column1, Column2);
You can also create a trigger for UPDATE:
CREATE TRIGGER
BEFORE UPDATE ON my_table
FOR EACH ROW
SET new.new_content = CONCAT(Column1, Column2);

How to do a multiple insert using LAST_INSERT_ID() MySQL?

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);

Avoid entering duplicate entries based on date, without using select statement

I am running a insert statement to insert data, but I want to check for any duplicate entries based on date and then do an entry.
All I want is if today a user enters product_name='x', 'x' is unique so that no one can enter product name x again today. But of course the next day they can.
I do not want to run a select before the insert to do the checking. Is there an alternative?
You can either use
1. Insert into... on duplicate update
2. insert.. ignore
This post will answer your question
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
You can use the mysql insert into... on duplicate update syntax which will basically enter in a new row if one isn't there, or if the new row would have caused a key constraint to kick in, then it can be used to update instead.
Lets say you have the following table:
MyTable
ID | Name
1 | Fluffeh
2 | Bobby
3 | Tables
And ID is set as the primary key in the database (meaning it CANNOT have two rows with the same value in it) you would normally try to insert like this:
insert into myTable
values (1, 'Fluffster');
But this would generate an error as there is already a row with ID of 1 in it.
By using the insert on duplicate update the query now looks like this:
insert into myTable
values (1, 'Fluffster')
on duplicate key update Name='Fluffster';
Now, rather than returning an error, it updates the row with the new name instead.
Edit: You can add a unique index across two columns with the following syntax:
ALTER TABLE myTable
ADD UNIQUE INDEX (ID, `name`);
This will now let you use the syntax above to insert rows while having the same ID as other rows, but only if the name is different - or in your case, add the constraint on the varchar and date fields.
Lastly, please do add this sort of information into your question to start with, would have saved everyone a bit of time :)

If mysql db table does not contain row with specific ID , add data to the table

Hi i'm new to php and mysql.
I'm wondering how can i use PHP to check if a table in my mysql database contains a ROW which have the specific ID and if not add the data to the table .
For example,
Table structure:(Table name : record)
ID , DATA
i have ID=123 and DATA=hello stored in a variable in the php code , how can i use php sql query to find out whether the data exist by checking using its ID in the table , if not , INSERT the ID and DATA into the table.
I hope you understand.
p/s i have connected the php script to the database
Make the ID UNIQUE:
CREATE TABLE my_table( ID INT UNSIGNED UNIQUE...
then use INSERT IGNORE:
INSERT IGNORE INTO my_table( ID, DATA ) VALUES( some_id, some_data )
IF NOT EXISTS(SELECT 1 FROM structure WHERE ID = <yourid>)
INSERT INTO structure (ID, DATA) VALUES(<yourid>, <yourdata>)
Just replace INSERT with REPLACE.
http://dev.mysql.com/doc/refman/5.5/en/replace.html
Another option:
INSERT INTO record(id, `data`) SELECT 123, 'hello'
FROM new_table WHERE NOT EXISTS (SELECT id from record where id = 123 );
If your ID is unique key, then you can directly try to insert the row. If that ID is already in the table, the database would not let you insert it and will return error. Else you have to first run a SELECT statement to see if this ID exists in your table and if not insert it.
Also this thread will help you a lot I think How to 'insert if not exists' in MySQL?

Categories