Insert into 2 table and set both foreign key auto increment - php

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

Related

On Duplicate of entire rows of same values how to increase count?

I have a table using php mysql and using pdo for fetching records.
I want to know sql query so that if I insert row of all same values of same fields(duplicate row). It should insert new row by upgarding the count which is also one of the field
INSERT INTO table_name (column1, column2, column3, column4)
VALUES (value1, value2, value3,values4)
ON DUPLICATE KEY UPDATE count = count + 1;
this is hypothetical example
column2 is an id, which is foreign key constraints of another table2,
column3 is an id, which is foreign key constraints of another table3,
column4 is an id, which is foreign key constraints of another table4
total 4 tables I have. My table looks like this
Sno | column2_id | column3_id | count | column4_id
1 | column2_value | column3_value | 1 | column4_value
I have fetched all three tables data through id and show in table 1.
I have different values only 5 id in table 2 which have corresponding values.
if I insert new row of duplicate values it should insert by increasing count values.
By default I have taken count as 1.
I didn't understand very well your request.
But if I understand correctly you want to update a row if it is duplicate?
If so you can just use an ON DUPLICATE KEY UPDATE
For example :
INSERT INTO table_name (column1, column2, column3, number)
VALUES (value1, value2, value3, number)
ON DUPLICATE KEY UPDATE number = number + 1;

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

Update another table when another one is updated

I'm not quite figuring out how to do what I'm after.So what I'm making is an online game.When a user buy's a new car I do an INSERT:
$c->query("INSERT INTO user_cars (carid, userid, acc, speed) VALUES ('$buyid','$id','$acc','$speed')");
Now I have another table that I need to insert info to right after the query above FROM the query above.What I need is the carid .The user can have more than 2 cars.What should I do now?
You have multiple options:
You can build a trigger to insert a new row in table2, when row is inserted in the cars table (Read more here http://dev.mysql.com/doc/refman/5.5/en/trigger-syntax.html)
There is this function mysql_insert_id() which returns the last inserted id ( Read more here http://php.net/manual/en/function.mysql-insert-id.php )
If you use PDO , there is a smillar command for it
etc.
This is a basic demonstration of the trigger you would want to create. For illustrative purposes I've also included the ddl and an example insert into your user_cars table to show that another table, which I've called "your_other_table" receives the insert (just the carid value) of an insert going into the user_cars table.
Fiddle:
http://sqlfiddle.com/#!9/f76a7/1/0
(notice how "your_other_tabe" has one row with the carid of the insert into "user_cars", despite having no direct inserts into itself)
delimiter //
create table user_cars
(
carid int,
userid int,
acc int,
speed int,
constraint id_pk primary key (carid, userid)
)//
create table your_other_table
(
carid int
)//
create trigger your_trigger_name before insert on user_cars
for each row begin
insert into your_other_table (carid)
values (new.carid);
end
//
insert into user_cars values
(1, 2, 3, 99)//
delimiter ;
select *
from your_other_table;
Output:
| CARID |
|-------|
| 1 |
This is the only portion of the above sql that creates the trigger:
delimiter //
create trigger your_trigger_name before insert on user_cars
for each row begin
insert into your_other_table (carid)
values (new.carid);
end
//
delimiter ;

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