Database Allow Duplicate Entry for Foreign Key - php

I have two tables users, and posts. The posts table has a column with the foreign key user_id which corresponds to the id in the users table. If another row is inserted to the posts table and it has the same value in the user_id column as another row, I get an error:
"Duplicate entry '4' for key in 'user_id'"
How can I allow for duplicate entries in this user_id column?

I went into the relational view, edit keys, and changed it from unique, to index. Thanks to Cory.

Related

PHP/SQL/Mysql/phpmyadmin - Foreign Keys

I'm building a shop for school purposes. I have finished my shop but i didn't joined tables and used foreign keys (requirement) because i forgot..
I have a newbie 'question' about foreign keys.
PRODUCTS RATING TABLE:
rate_id (id of the rate),
rate, (stars 0 to 5)
comment (user input textarea),
user_id (id of the user who commented the product),
product_id (id of the product that was commented)
USERS TABLE:
`id` (id of the user),
`email` (email of the user),
`name` (name of the user),
`age`,
`username`,
`password`,
`profile_pic`,
`role` (ADMIN/USER)ยด
When i enter a comment on X product (if (isset($_POST['comment_rating])):
$sql = mysqli_query($link, "SELECT id FROM users WHERE username='$user_id'");
and then later:
$sql = "INSERT INTO products_rating (rate, comment, user_id, product_id)
VALUES ('$rate_text', '$comment', '$user_id', '$product_id');
FINAL: What i want to know is, what do i need to change in my code if i add a foreign key? And should i add a foreign key in this particular case? I must interligate all tables, and I don't understand much about joins / foreign keys. If i wasn't clear let me know. Thank you for you help!
The idea of a foreign key is pretty straightforward.
In the products_rating table, we are storing a value for user_id.
And the value that we stored there is a value of id column from a row in the user table. This establishes a relationship between the row in products_rating an a row in user.
We could get the name and email address of the user that left a product rating
SELECT u.name
, u.email
, r.rate
, r.comment
FROM product_rating r
JOIN user u
ON u.id = r.user_id
WHERE ...
A FOREIGN KEY is a constraint that implements a rule. The rule we want to implement is that we want to allow only valid user.id values to be stored in product_rating.user_id.
For example, if we attempt to store a value of '42' in the product_rating.user_id column, the database is going to check that the value '42' appears in a row in the user table (in the id) column.
The syntax that we use to implement that constraint would be on the product_rating table:
ALTER TABLE `product_rating`
ADD CONSTRAINT -- we are adding a constraint
`FK_product_rating_user` -- the name we assign to the constraint
FOREIGN KEY -- the type of constraint
(`user_id`) -- the column(s) in this table
REFERENCES -- refer to
`user` -- the name of the "foreign" table
(`id`) -- the column(s) in the "foreign" table
We can add some additional configuration that affects behavior...
ON DELETE RESTRICT
ON UPDATE CASCADE
This implements a rule... if we attempt to assign a value to user_id column in this table, and that value is not found in a row in user table id column, an error is thrown, and the statement fails.
This rule also says that if we attempt to remove a row from user, if there are any rows in product_rating that have a user_id value that matches the id value of the row we're deleting, an error is thrown, and the statement fails.
The rule also says that we update a row in user, and assign a new value to the id column, than any rows in product_rating that have a user_id value that matches the old id value will be updated, to assign the new id value to the user_id column... preserving the relationship between the rows.
Also note that this implies a "one-to-many" relationship. A user can be related to zero, one or more product_rating. A product_rating is associated with one user. (If the user_id column allows for NULL values to be stored, a NULL value represents that the row in product_rating is not associated with any user.)
That's just a rough overview of FOREIGN KEY constraints.
The basic idea is that we establish a relationship between rows by storing a common value. In the example we use, a common value of '42' in the id column of a row in the user table, and in the user_id column of one (or more) row(s) in the product rating table.
With no foreign key constraint defined, the database allows us to store any value in the user_id column. We could store '43' or '8670', and it doesn't matter if those values appear in user.id or not.
The foreign key we defined constrains (restricts) what values we can store in the user_id column. When we attempt to add or modify a row in product_rating, the database checks the value of the user_id column, and if a non-NULL value doesn't reference a row in user, an error is raised.
Note that the foreign key constraint does not cause the user_id column to be automatically populated. If we want to establish a relationship to a row in user, we have to supply a value for user_id.

How come I cannot insert data mysql after I add foreign key?

After I add foreign key into my table, I cannot insert data into it.
for example, Table Fruit with id, order_id , amount. I add foreign key Fruit (order_id) reference another table. After that, I cannot INSERT INTO amount or other columns, but I can only INSERT INTO the foreign key order_table. How can I solve this problem? Appreciate.
when you define a foreign key in a table .after that when you will go to insert values into that table there will be drop down menu in front of foreign key .
so you have to choose a vale either 1 or 2 etc then data will be inserted(remember firstly you have to insert data into that table from which you are bringing foreign key so that there may be some value that after ward you browse that in another table in drop down)
Your Fruit table has a column that referenced to another table. So you need to define order_id in each Fruit row. Fruit row can not has empty value in order_id column. Try to insert a row contains order_id into Fruit table.
I think you may have your foreign key relationship configured backwards. When you are trying to insert into the table Fruit, MySQL is expecting order_id to be a valid record from the order_table.
I would expect that the table Fruit would reference to multiple orders, so the order_table should have a foreign key relationship to the id column from the Fruit table.

Why show does mysql show a Duplicate entry error

Duplicate entry '20' for key 'user_id'
$userid = its foreign key (20)
$query = mysql_query("insert into qualification (q_id,course_name,institute_name,pass_year,user_id) values ('','$coursename','$institutename','$passyear','$userid')") or die(mysql_error());
Does anybody have an idea on how to skip this error and add multiple record on the same userid ?
When you get this error, you have a UNIQUE or PRIMARY key constraint for user_id in your database. As Marc B already said. Remove the unique constraint from the user_id.
You asked Marc:
Why remove unique constraint?
Simply because then you can't have two records with the same user_id in your table. Then you also can't use it as a key for table. You can still use an index on user_id to speed up queries for this field.

Using ON DUPLICATE KEY UPDATE with 2 keys

I have a table with columns id, user_id, post_id, like, views. When a user click the Like button, a row will be added to the table with the corresponding user_id and post_id, and like will be set to 1. If the row already exist and the like column already is 1, nothing will happen.
When the user visits a particular page, a row will be added to the table with the corresponding user_id and post_id, and view will be set to 1. However if the row already exist, the value in view will be incremented.
Problem: I tried using INSERT INTO mytable ... ON DUPLICATE KEY UPDATE like = 1, but the primary key of the table is id and not user_id or post_id. If I set the primary key to either user_id or post_id, there will be a problem because the row will only be duplicated if there exist a row with the same user_id and post_id.
In this situation, how should the query be built?
Or will a better situation be to split the table into 2 tables, one for likes and 1 for views. If this is the case, I still need to make the row unique based on both user_id and post_id columns.
Or do multiple SQL queries?
Please advise, thanks!
I would suggest that you have a table for likes, and then in whatever table that you keep posts in, you add a row for views. So whenever this post is viewed, you simply update the view value for that post to view = view + 1.
Now to address the problem that you outlined about the primary keys, you should note that you can use a unique key in that scenario, which can apply to multiple columns and would fix the issue that you ran into. So for example if in your scenario you had a unique key that encompassed both the userid and postid, your database would not allow for two different rows in that table with the same userid and postid.
So for future reference, use a unique key if you need to :)
discard the id as primary key
use two tables
make primary key on (user_id, post_id)
when handle insert like, do a insert ignore
when handle insert view, do a insert .. duplicate key update view = view+1

SQL - Unique Foreign Key on per Foreigner Basis

Is this possible to achieve? A table of Interests for example, correspond to a table of users, with foreign key user_id corresponding to user(id), can I enforce uniqueness for column interests.name on a user_id basis?
So you basically don't want multiple rows with the same interest for a single user_id, correct?
You need to create a unique constraint (index) on the combination of user_id and interest_id.
alter table interests add unique index(user_id, interest_id);

Categories