Mysql not insert records - php

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

Related

Sql INSERT INTO combining value and select failure

I wanted to insert two values, one is filled by a fixed number and the other one is the id from another table.
Now I got the error
#1242 - Subquery returns more than 1 row.
INSERT INTO table1 (value1, value2) VALUES
(6 , (SELECT id FROM table2 WHERE name = 'Peter'))
Maybe you can help me.
If you want to insert record into your table1 for every record in table2 where name is Peter this approach should work.
This insert query will insert all records from table2 where name is "Peter" into table1. If you want to insert only one record you could use LIMIT as Macmee has explained in his answer
insert into dbo.table1
(
value1,
value2
)(
select
6,
table2.id
from
table2
where
name = 'Peter'
)
try using LIMIT 1:
INSERT INTO table1 (value1, value2) VALUES (6 , (SELECT id FROM table2 WHERE name = 'Peter' LIMIT 1))
This way in your nested query (SELECT id FROM table2 WHERE name = 'Peter' LIMIT 1) it will only return the first match, and your insert should go through.
Keep in mind that if your intent was to insert new rows for EVERY row in table2 who's name is "Peter" then this will only insert the first one.

SQL Statement INSERT, on duplicate columns UPDATE

I have an SQL Table that contains a list of items that users can have linked to their profile. The SQL table looks something like this:
Item_Activity_ID Item_ID User_ID Status Date-Added
1 1 1 1 2015-06-08
2 2 2 1 2015-06-08
3 1 1 0 2015-06-09
The entry shows that someone with the user with id of 1 added item id 1 twice, and the only thing that was changed was the date and status. I want to make it so that when given an INSERT statement such as:
INSERT INTO items (Item_ID, User_ID, Status, Date_Added) VALUES ('$x', '$y', 1, CURDATE()) IF EXISTS SOME Item_ID = $x AND User_ID = $y UPDATE items SET Status = 1, Date_Added = CURDATE() WHERE Item_ID = $x AND User_ID = $y
Item_Activity_ID is an auto_incremented primary key index. How can I accomplish this in one query? Two users can have the same item, but where should never be repeat entries of the same user id and item id.
First, create a unique index for Item_ID, UserID combination,
Then, use the INSERT ... ON DUPLICATE KEY UPDATE statement:
INSERT INTO items (Item_ID, User_ID, Status, Date_Added)
VALUES ('$x', '$y', 1, CURDATE())
ON DUPLICATE KEY UPDATE Status = VALUES(Status), Date_Added = VALUES(Date_Added))
P.S. make sure to sanitize $x and $y to prevent SQL injections!
I would start by adding a unique key index:
ALTER TABLE items
ADD CONSTRAINT uc_UserItem UNIQUE (Item_ID,User_ID);
Then, you can just modify your insert query:
INSERT INTO items (Item_ID, User_ID, Status, Date_Added) VALUES ('$x', '$y', 1, CURDATE()) ON DUPLICATE KEY UPDATE Status=VALUES(1), Date_Added=VALUES(CURDATE());
Try to perform the update first supposing that the user and item already exist. Then check if this update affects any rows (using ##rowcount, in SQL Server).
If not then perform an insert.
Don't forget to put the above two statements in a transaction... ;)
Normal way would be to set a composite constraint at the db level. If you are using mysql and phpmyadmin you do this in the table structure view.
Check both fields (I guess 'user_id' and 'item_id') and click the 'unique' button.
After that is set you can just append
ON DUPLICATE KEY UPDATE status =1, date_added=CURDATE().
It will update the row that violated the constraint you created

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

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

SQL Query for fetching the data of users not submitting their time for a particular week?

I have two tables one containing user information and the other having their time entered for the weeks as below!
Table1
------
UserID (PK)
Username
Email
Phone
Table2
------
Timesheetid (PK)
UserID (FK)
Weekenddate(date)
Totaltimeworked
From the above tables I want to retrieving the user ID,username and email from TABLE 1 for the user who have not entered information in the table 2 based on the weekend date(weekend date is selected in the search field and not hardcoded).
Please help me with the SQL query to create this table .
Try this working code on SQL Fiddle. As you haven't posted any data and columns definition I assume weekenddate to be a varchar.
On the condition Weekenddate = 'sunday' OR Weekenddate = 'saturday' substitute the values sunday and saturday by your parameter value. In fact, you will only need to use on of the clauses of the condition as you have only one parameter with the weekend value. Then just wrap the code into an
`INSERT INTO your_new_table (UserID, Username)`
Considering your Totaltimeworked column is up to date:
CREATE TABLE newTable(
UserID int not null,
Weekenddate date not null,
FOREIGN KEY(UserID) REFERENCES Table1(UserID)
ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO newTable (UserID, Weekenddate)
(SELECT (UserID, Weekenddate) FROM Table2 WHERE Totaltimeworked > 0);
Or if you meant just for 1 specific week don't add the Weekenddate to newTable and modify query as
INSERT INTO newTable (UserID)
(SELECT (UserID) FROM Table2 WHERE Totaltimeworked > 0
AND Weekenddate = 'year-month-day');

Mysql select from a table and insert into another

I have a mysql table called jos_users_quizzes with the following columns:
id
quiz_id
user_id
I have a second table called jos_users with this columns
id
name
username
department
the user_id on first table is linked with the id of second table so
quiz_id = id (jos_users)
How can build a query to multiple insert the ids of a selected department into the jos_users_quizzes table... in one click
I am thinking meabe a sub query or a loop, but no sure how.
Thanks in advance!
INSERT jos_users_quizzes (quiz_id, user_id)
SELECT $quizID, id
FROM jos_users
WHERE department = 'selected department'
With INSERT ... SELECT, you can quickly insert many rows into a table from one or many tables. For example
INSERT INTO jos_users_quizzes (quiz_id)
SELECT jos_users.id
FROM jos_users WHERE jos_users.department = 100;

Categories