PHP Mysql Foreign Key - php

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

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.

implementing referntial integrity with php mysqli

i have three tabs in my Db:
1.pers_info(id(primary), name ,....)
2.contacts(c_id(primary), phone, email, ...)
now 1 person can have multiple rows in contacts tab.
thus to minimize redundancy i made another tab contact_relation(id (foregin key references pers_info(id), c_id (foregin key references contacts(c_id))
i successfully created the relation and also was able to insert apt entries(related id and c_id) to it "using last_insert_id();" to extract id and c_id required.
now the problem..
i dropped tab contacts_rel. and created it this way :
CREATE TABLE contacts_relation (
id INT NOT NULL,
cid INT NOT NULL,
FOREIGN KEY (id)
REFERENCES pers_info(id)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (c_id)
REFERENCES contacts(c_id)
);
if now i try to insert into tab cont_rel, it gives error :
cannot add or update a child row foreign key constraint fails.
which makes sense..
i was hoping that adding constraints in the defn of tab cont_rel would save the hassle of inserting entries in it manually using "last_insert_id();"
so is there a way, i could maintain ref integrity with new data
coming.. thanks.
Why the third table? When you many to many relation you need intermediate table. You have one to many relation so two tables are sufficient. Table contacts need FK to table pers_info. Add it if you don't have already.
Here's a simple transaction example with LAST_INSERT_ID(): SQL INSERT INTO multiple tables
Some info about foreign keys and altering table:
Add Foreign Key to existing table
http://dev.mysql.com/doc/refman/5.0/en/alter-table.html

MYSQL- Create and store primary key in master and child table

I got stuck while insertion into database tables.
I have below tables.
I dont have any fields which can be make as Primary key.
Here "eme_request" and "eme_attachment" is master tables.
I want to know that how can I insert into tables ?
These tables(eme_request, eme_gf_relevent, eme_non_gf_relevent, eme_attachment) are getting insertion on one form request.
So I am not getting how to generate primary key in master table and how to insert into child table with that primary key as a Foreign key ?
In eme_request table REQ_ID (your PK) is type of varchar. If you can change it to INT and add flag AUTOINCREMENT, you will get automatically generated key.
If you can't change type of REQ_ID (you need it to be char), just add abstract PRIMARY_KEY int column and use it.
After inserting into table with autoincrement column you can receive assigned key with
https://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id so it can be used as FOREIGN KEY for other tables.

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 :).

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