PHP/SQL/Mysql/phpmyadmin - Foreign Keys - php

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.

Related

Insert Into on Duplicate Update creates me an unwanted row

I have a SQL query as follows-
"INSERT INTO users(id, rank) SELECT v.user, v.vote FROM votes v WHERE
v.assertion = '$ID' ON DUPLICATE KEY UPDATE
rank = ( CASE WHEN v.vote = '1' THEN rank+50 WHEN v.vote = '-1'
THEN rank-200 WHEN v.vote = '3' THEN rank+100 ELSE rank END)"
applied on a database with a table users with and id and rank field, and a votes table with a user and vote field. I have to update the rank of the users in the users table based on their vote.
I really like this kind of query, but I've noticed a problem: every time I execute this from my PHP script the query adds a row to the users table completely empty (with only an ID, which is A_I, and a rank of 1, when usually there would be other field as well). I can't really wrap my head around why this happens.
Any help/idea?
Your table does not have a primary key first provide a primary key to id
run this sql query
alter table user add primary key (id)
and than try it will work
There are two possible reasons :
The id column is not the primary key, and probably you table doesn't have a primary key at all.
Create a primary key like this :
alter table user add primary key (id)
If you insert an value of 0 in an auto increment column, a new id is generated. An auto incremented column must not contain the value 0.
There is also a more general problem with your approach : in fact you only insert the user id and the rank, other compulsory fields in the table (username) are missing. The insert part does not seem to be valid for this reason. If you use an insert on duplicate key update, you must make sure that the result is correct which ever of insert and update is executed.

PHP Mysql Foreign Key

I have two mysql tables:
1- customers
2- lite_order
customers table columns:
customer_id primary key and Auto Increment field
Email
hashed_password
lite_order filed contains all the order fields that maybe more than one order belong to same customer and i have many fields. most important ones:
lite_order_id primary key and Auto Increment field
customer_id i made it as "index" and from the relation view on phpmyadmin i selected this column as the foreign key to reference to the primary key in the customers table.
The problem is when a new customer signs up, his information goes to the customers table, an d he fills an order form that its data should go to the lite_order table i get an error on this step:
Error: Cannot add or update a child row: a foreign key constraint fails (`DB_NAME`.`lite_order`, CONSTRAINT `lite_order_ibfk_2` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON UPDATE CASCADE)
How can i fix this error? i have the customers table working and the customer_id in the customers table have a value now, but i need this value goes also to the customer_id column in the other table once the order form is submitted. and i get this error that!.
By assigning the foreign key "customer_id" into the table "lite_order", you assure a reliability of your data. I mean a lite_order can't be inserted without having a customer.
So you have to insert your customer first, then yours orders.
Depending on what extension you use (mysql, mysqli, pdo), you get the last inserted customer_id by :
-mysql
-mysqli
-pdo

A foreign key constraint fails

I am relatively new in php and mysql.The problem that i am facing while i inserting value in my leave table.My leave table containing following column..
1.lid(INT primary key)
2.empname(varchar)
3.username(varchar)
4.nod(INT)
5.sdate(DATE)
6.edate(DATE)
7.reason(varchar)
8.action(varchar)
9.empID (INT FOREIGN KEY)
here empID is the foreign key references from users table. The problem that im facing while inserting values into the leave table.ERROR is given below
Cannot add or update a child row: a foreign key constraint fails (db_attendance1.leave, CONSTRAINT leave_ibfk_1 FOREIGN KEY (empID) REFERENCES users (empID))
here i just send the query and here it is..
mysql_query("INSERT INTO `leave`
(`empname`, `username`,
`nod`, `sdate`, `edate`,
`reason`,`action`)
VALUES ('$empname', '$username',
'$nod', '$sdate',
'$edate', '$reason','');",
$dbCon) or die(mysql_error());
You can put
SET FOREIGN_KEY_CHECKS=0;
and run your query. Once you are done again set it back to 1 by
SET FOREIGN_KEY_CHECKS=1;
A foreign key constraint means that you one table doesn't accept inserts, updates or deletes that would 'break' the foreign key. This means, you can't update a EmpID if the new EmpID doesn't exist in the users. You can't add a new EmpID if it doesn't exist in the users table, etcetera.
So to solve this issue, you need to make sure that the EmpID you're trying to add to table 'leave', first exists in table 'users'.
Foreign keys can be a real powerful item, but can be a real pain too. Since the DB you're working on had foreign key constraints, I suggest you read on them a bit: http://en.wikipedia.org/wiki/Foreign_key
Borniet, you helped me solve my similar problem.
#OP - All I had to do to fix this was create a corresponding row in the table so that the foreign key would exist.
E.g. Table 1 has column Name
Table 2 has column friends_name, a foreign key tied to Name in table 1.
I got this error because I was trying to insert a row into table 2, where the friends_name referenced a non existing Name in table 1. So I created the name and we're off to the races :).

Search in MySQL foreign field

I'm fairly new to PHP and MySQL.
I have two tables as follows:
1.`users`: `id`//primary key
: `name`//user's name
2.`events`: `u_id`//index key and foreign field to users' id
: `u_name`
A user will input an id in a form. That id will be searched in the users table and the relevant details will be taken and inserted in the events table.
I've created the foreign fields and and till now I made a function that took id as a variable and returned details from the users tables as variables which I then inserted in the events table. But then, it meant using "a lot" of variables and I thought what was the use of foreign field.
I'm still learning PHP and don't know how to find and insert using FOREIGN fields from one table to another. I just know how to create foreign fields. Please help.
Is this what you're talking about?
This is how foreign key is created.
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
);
Apologize if I didn't understand your question
UPDATED
INSERT table1 (col1, col2, col3)
SELECT col1, col2, col3
FROM table2
WHERE col1 = 'xyz'
Hope this helps
You don't need to store the user name in the events table. The point of the foreign key is that you only need to store the user ID in the events table, because that is a REFERENCE to the user.
To get the user name for an event, say event number 6, you would do
select name from users join events on users.id = events.u_id where events.id = 6
So, you should not be trying to insert user data into the events table. Just put the ID in there, and the user data will be available for you to retrieve using the foreign key.

How to set a foreign key and retrieve or delete data from multiple tables?

I am new to php and mysql. I created a database named 'students' which contain two tables as 'student_details' which have fields like 'ID, Name, Age, Tel#, Address' and another table as 'fee_details' which have fields like 'ID(student_details table ID), Inst Id, Date, Receipt No'.
I want to set a foreign key and retrieve data from both tables when a student paid their fees and if a student passed out or discontinued I want a delete option to delete his all records from my tables. So please help me to solve this by PHP code and displays it in HTML while using a search form.
Enforcing referential integrity at the database level is the way to go. I believe when you said you wanted the delete "to delete his all records from my tables" you meant deleting the row and all its child records. You can do that by using foreign keys and ON DELETE CASCADE.
CREATE TABLE students
(
student_id INT NOT NULL,
name VARCHAR(30) NOT NULL,
PRIMARY KEY (student_id)
) ENGINE=INNODB;
CREATE TABLE fee_details
(
id INT,
date TIMESTAMP,
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
ON DELETE CASCADE
) ENGINE=INNODB;
With this, when a student is deleted from the students table, all its associated records will be deleted from fee_details.
you can try mysql_query() and mysql_assoc_array()

Categories