PHP, SQL insert value into tables that are linked together? - php

I have 2 tables,
Table User:
Columns-> id, name, age, position, department, phone
Table Phone:
Columns id, u_id, u_phonetype (foreign key is user.id with on delete cascade and update cascade).
I want to perform this INSERT INTO sql with the u_phonetype from the Phone table:
INSERT INTO `user` (`id`, `name`, `age`, `position`, `department`,
`phone`) values ("'.$name.'", "'.$age.'", "'.$position.'", "'.$department.'", "'.$phone.'") ;
How do I insert into the values of u_phonetype into this SQL? Would I be performing a JOIN?

using php you would just need to use 2 / 3 queries to get this done.
// insert your user
INSERT INTO users (columns) VALUES(vals);
// get the last id
SELECT id FROM users order by id desc limit 1
// this is also work if you just do
SELECT id FROM users where name='name' and age='age' "and whatever values you have";
// then insert into phone with the id retrieved from above
INSERT INTO Phone (columns) VALUES(vals);
3 step process but under the same connection it should be ok

What about
LAST_INSERT_ID();
INSERT INTO table1 (column1,column2) VALUES ('test', 1);
SET #last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO table2 (column3,column4,column5) VALUES (#last_id_in_table1, 2, 3);

Related

pdo - How INSERT table value in Select and additionally string

He needs to insert a table of values from a select query and additionally string
$query=("INSERT INTO table1 (a,b,c,d) VALUES ('a',SELECT b,c,d FROM table WHERE x=1)");
Could you as him to try the following:
INSERT INTO table1 (a,b,c,d) VALUES (SELECT 'a',b,c,d FROM table WHERE x=1)

SQL insert into select from multiple fields

I have a table 'users' with a column of 'ID'. I want to select 2 different 'ID's' based on 2 different parameters and insert them both into another table known as 'jobs'.
INSERT INTO jobs (customer_id, client_id)
SELECT id, id from users
WHERE username = ?
AND username = ?
Basically I want to get the ID of two different people and insert them both into the new table.
I would then bind the parameters to ?, and they would look something like 'john' and 'steve'. I have tried the code above but I know it is the wrong syntax. Any ideas would be greatly appreciated. Thanks
You could use a self-join:
INSERT INTO jobs
(customer_id, client_id)
SELECT customer.id, client.id
FROM users customer
JOIN users client ON customer.username = ? AND client.username = ?
Or, you could use subqueries:
INSERT INTO jobs
(customer_id, client_id)
VALUES (
(SELECT id FROM users WHERE username = ?),
(SELECT id FROM users WHERE username = ?)
)
Well, you could use subquerys
INSERT INTO jobs (customer_id, client_id)
VALUES (
(SELECT field from table where id = 2),
(SELECT field from table2 where id = 12)
)
I'm not pretty sure about the sintax, since I haven't tested, but I'm guessing it could solve it.
I often use such things in WHERE or in the SELECT statement. Just remember to return a single field and a single row in the subquerys.

Insert into 2 table and set both foreign key auto increment

I have a database with two tables. When a user posts an article, it will be inserted into both tables, (2 queries in one file)
I use post_id as foreign key, both tables post_id auto increment. Will foreign keys be messed up? For example if users A and B query the database at the same time.
Table 1
post_id user...
1 A
2 B
Table 2
post_id content...
1 A
2 B
First off you can't have auto increment on both tables.
Usually, what you do is insert in table 1, get the ID of the just inserted row.
Then you use this ID, to insert in table 2 which references table 1.
See: mysqli::$insert_id at
http://www.php.net/manual/en/mysqli.insert-id.php
Example:
$query = "INSERT INTO table1(user,whatever) VALUES ('A','something')";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
$query = "INSERT INTO table2(post_id,content) VALUES ($mysqli->insert_id,'This is content')";
$mysqli->query($query);
You could also do this using a stored procedure based on: stackoverflow.com/a/1723325/1688441
DELIMITER //
CREATE PROCEDURE new_post_with_content(
user_id CHAR(5), content_text CHAR(100)
BEGIN
START TRANSACTION;
INSERT INTO table1 (user)
VALUES(user_id);
INSERT INTO table2 (post_id, content)
VALUES(LAST_INSERT_ID(), content_text);
COMMIT;
END//
DELIMITER ;
And you call it like so:
CALL new_engineer_with_task('A','This is the content');
Why not use table1 as user table and second with posts?
users
user_id(autoinc) username
1 A
2 B
3 C
posts
post_id(autoinc) user_id posts_text
1 2 text
2 1 other text

INSERT on update. Compound Key

I have a question on This MySQL statement.
I got this from this post
However, I am not sure how to structure the query when I have the table like this.
TableA
--------
id ==> Auto Increment field
question_id
form_id
member_id
event_id
admin_id
desc
is_cand_field
c_field_id
In this, question_id, form_id, memmber_id, event_id, admin_id can be same. desc, is_cand_field, c_field_id can change. When inserting, I want to check if this combination exists. If exists, I want to update the last 3 fields. If not, I want to insert a record.
Is this possible with the above referred query. Its not clear from the page.
Add unique key on combination of these fields:
ALTER TABLE `tablea` ADD UNIQUE INDEX `compound_key` (`question_id`, `form_id`, `member_id`, `event_id`, `admin_id`);
Insert values and add update section:
INSERT INTO tablea (`question_id`, `form_id`, `member_id`, `event_id`, `admin_id`, `desc`, `is_cand_field`, `c_field_id`)
VALUES (1, 2, 3, 4, 5, 1, 0, 1)
ON DUPLICATE KEY UPDATE `desc` = VALUES(`desc`), is_cand_field = VALUES(`is_cand_field`), c_field_id = VALUES(`c_field_id`)
You can add multiple rows in the ON DUPLICATE KEY UPDATE section.
INSERT INTO TableA (form_id, member_id, event_id, admin_id, desc, is_cand_field, c_field_id)
VALUES (2, 3, 4, 5, 'b', 0, 1)
ON DUPLICATE KEY UPDATE desc='a', is_cand_field=1, c_field_id=2

Mysql not insert records

I have two tables: employee and employee_group. After insert to first table I will get last inserted id from this table. Next I need insert to table employee_group. SQL:
INSERT INTO employee_group (employee_id, group_id)
SELECT {$currentEmpId}, group_id
FROM employee_group
WHERE employee_id = {$anyId}
MySQL has been returned TRUE. But records have not inserted.
I noticed if try insert records for previous inserted employee then query will be successful. Example:
Insert to employee, will return $currentEmpId as last inserted id
INSERT INTO employee_group (employee_id, group_id) SELECT {$currentEmpId - 1}, group_id FROM employee_group WHERE employee_id = {$anyEmpId}
Or if I tried insert records for current employee and previous at the same time then first query will be unsuccessful but second query ok.
The database has not triggers, foreign keys or functions. Nothing, just data.
I'm in a deadlock.
UPD: If I take records to php variable then foreach it and insert each record as one item like INSERT INTO employee_group (employee_id, group_id) VALUES (xxx, yyy) I will get this problem too.
INSERT INTO employee_group (employee_id, group_id)
VALUES({$toEmpId},{SELECT group_id FROM employee_group WHERE employee_id = {$fromEmpId}})
Check it out ..
Try this
INSERT INTO employee_group (employee_id, group_id)
VALUES({$toEmpId},{SELECT {$toEmpId}, group_id FROM employee_group WHERE employee_id = {$fromEmpId}})

Categories