I'm not sure if my foreign key is working - php

I've made a system where employees can send feedbacks.
Feedback form:
Now I have two tables in my database, tbl_feedback and employee:
tbl_feedback:
employee:
The employee_id in my tbl_feedback is a foreign key that references id in employee table.
My question is, is it really necessary to put Employee ID on my form for it to work? Because I noticed that when I remove Employee ID on the form, I get an error. Does that also mean I didn't set the employee_id column to a foreign key? properly?
Here's my insert feedback php code:
<?php
require_once ('database.php');
if (isset($_POST['send'])) {
$employee_id = $_POST['employee_id'];
$full_name = $_POST['full_name'];
$email = $_POST['email'];
$website = ($_POST['website']);
$message = ($_POST['message']);
{
$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insert_query = "INSERT INTO tbl_feedback (employee_id, full_name, email, website, message)
VALUES (?, ?, ?, ?, ?)";
$insert = $database->prepare($insert_query);
$insert->execute(array($employee_id, $full_name, $email, $website, $message));
echo "<script>alert('Successfully sent!'); window.location='feedback.php'</script>";
}
}
?>
Here's how I created tbl_feedback:
CREATE TABLE tbl_feedback (
id int NOT NULL AUTO_INCREMENT,
employee_id int NOT NULL,
full_name varchar(100) NOT NULL,
email varchar(100) NOT NULL,
website varchar(100) NOT NULL,
message varchar(100) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (employee_id) REFERENCES employee(id)
);

If you remove the employee information from your feedback form, without getting the information from another source, you will defineately have a problem.
The foreign key constraint you added to your tables just makes sure, that there is not feedback entry in your table, that has no corresponding employee to map it with.
This means, that it does not magically maps the two tables with each other and makes sure that each feedback has a linked employee, but rather throws an error for each feedback entry that can not be linked to an employee, based on the given id. The errors you encountered are therefore actually proof, that your foreign key constraint works correctly.
So eventhough you have a foreign key constraint, you still have to manage the mapping in your code.

If there is a Foreign Key in Table then table needs the key to be passed when inserting the data. It doesn't matter if you are passing via Form or getting your employee id from the database via PHP code.

Related

How to automatical add data to a table with a foreign key php [MariaDB]

How can I use php to add data to the foreign such that the IDs match:
In this example, I have a table for a 'member' and a separate table for 'emails'. A member can have multiple emails and therefore a separate table is created that stores emails with the member ID as a foreign key.
How can I write code that inserts data into both tables when fields have been submitted?
My most recent (unsuccessful) attempt:
PHP block:
$query=
"INSERT INTO Members(FIRST_NAME, LAST_NAME, TITLE, INSTITUTION) VALUES ('$first_name',
'$last_name','$title','$institution');
INSERT INTO EMAIL(Members_ID, EMAIL) VALUES
(LAST_INSERT_ID(), '$email');
INSERT INTO WEBSITE(Members_ID, WEBSITE) VALUES
(LAST_INSERT_ID(), '$website');";
mysqli_query($connection,$query) or die(mysqli_error($connection));
SQL Block:
CREATE TABLE Members(
ID INT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE,
FIRST_NAME TEXT(16),
LAST_NAME TEXT(16,
TITLE TEXT(7), /** 7 CHARS for 'Student'*/
INSTITUTION VARCHAR(2048),
PRIMARY KEY(ID)
);
CREATE TABLE EMAIL(
Members_ID INT UNSIGNED NOT NULL UNIQUE,
EMAIL VARCHAR(2048),
FOREIGN KEY (Members_ID) REFERENCES Members(ID)
);
CREATE TABLE WEBSITE(
Members_ID INT UNSIGNED NOT NULL UNIQUE,
WEBSITE VARCHAR(2048),
FOREIGN KEY (Members_ID) REFERENCES Members(ID)
);
You could use, for example mysqli_multi_query, after having retrieved the ID assigned to the first insertion (I wouldn't rely too much on the LAST_INSERT_ID() in this case):
$conn = mysqli_connect(...);
$query = "INSERT INTO Members (FIRST_NAME,LAST_NAME,TITLE,INSTITUTION) VALUES ('$first_name','$last_name','$title','$institution')";
mysqli_query($conn, $query);
$lid = mysqli_insert_id($conn);
$query = "INSERT INTO EMAIL (Members_ID,EMAIL) VALUES ($lid,'$email');";
$query .= "INSERT INTO WEBSITE (Members_ID,WEBSITE) VALUES ($lid,'$website');";
mysqli_multi_query($conn, $query);

How to populate the child table with foreign key - MySql

I am working on MySQL database. I am new to it that is why I am facing a problem. The problem is populating the child table with foreign key which is referencing to the parent table. I have two tables employee which contains following columns
id as a primary key,
first_name
last_name
birth_date
and a borrowed table which contains following columns
ref as a primary key
employId as a foreign key
book
The employeeId is referencing the primary key id of the employee table. So simply it means the one employee with same id can borrow multiple books. When I insert some data into the employee table It get inserted, but when I have to insert data into the borrowed table, I have to manually insert the value in employeeId column. Isn't it supposed to be populated automatically. or I am misunderstanding the concept of the foreign key.
My SQL Code
$uname = "root";
$pass = "";
$sname ="localhost";
$db ="nady";
//Making database connection
$con = mysqli_connect($sname,$uname,$pass,$db);
$t1 = "CREATE TABLE IF NOT EXISTS employee (
id smallint(5) unsigned AUTO_INCREMENT NOT NULL,
firstname varchar(30),
lastname varchar(30),
birthdate date,
PRIMARY KEY (id)
) ENGINE=InnoDB";
$con->query($t1);
$t2 = "CREATE TABLE IF NOT EXISTS borrowed (
ref int(10) unsigned NOT NULL auto_increment,
employeeid smallint(5) unsigned NOT NULL,
book varchar(50),
PRIMARY KEY (ref),
FOREIGN KEY (employeeid) REFERENCES employee(id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB";
$con->query($t2);
if(!$con->query($t2)){
echo $con->error;
}
$i1 = "INSERT INTO employee VALUES(NULL,\"Nadeem\",\"Ahmad\",22)";
$con->query($i1);
$i2 = "INSERT INTO borrowed VALUES(NULL,1,\"Ahmad\")";
$con->query($i2);
if(!$con->query($i2)){
echo $con->error;
}
Simple what I need is ; For example an employee with id 1. Who borrowed 3 books. So in the borrowed table the employeeId column will have three rows with values 1 and different books name. My point is how would I populate the employeeId column when I am inserting the data into it. Let say, John have have borrowed three books and have id 1 then how would I insert data to borrowed table with employeeId of john. I need the query for it. and also query to retrieve the books borrowed by john.
The foreign key is used to link two tables, indicating that the field in a column
(employId from borrowed, in your case) refers to the PRIMARY KEY of another table (id from employee).
When you're inserting a new line in borrowed, you have to indicate the user that is taking that book, to insert it in that line. You have to know the user that is doing it. If you have foreign key, you need the id of that user, which is supposed to be his unique identifier. To insert that John has taken a book, you need to know that John's id is 1.
If the user is already in your employee table and you know his first and last name, you can get the id with a simple select...
SELECT id FROM employee WHERE first_name='John' AND last_name='Smith'
... and then you can do the insert with the id obtained.
If it's new user, you need to add the user first to employee, then get the new id and then insert the new line in borrowed, to do this without having to re-query to employee table to get the new id, you can use the PHP mysqli::$insert_id/mysqli_insert_id function, that gives you the PRIMARY key of the last query. For example...
$con->query("INSERT INTO employee (first_name,last_name) VALUES ('Mark','Whatever')");
$newemployeeid = $con->insert_id;
$con->query("INSERT INTO borrowed (employeeid,book) VALUES (".$newemployeeid.",'Awesome Book Title')");
I hope it helps
Your just need change these lines
$employee_id = $con->insert_id;
$i2 = "INSERT INTO borrowed VALUES(NULL,".$employee_id.",\"Ahmad\")"
first you get last insert id as $employee_id through a inser_id mysql predefined function then you add this $employee_id in borrowed table inserted query.
You can also use the MySQL-function LAST_INSERT_ID(). This function fetches the id from any previous INSERT statement, in the OPs case after inserting a new employee into employee table.
So the INSERT statement can be shortened to this:
INSERT INTO borrowed (employeeid, book) VALUES(LAST_INSERT_ID(),'Ahmad')";
Also note, that it is not required (and probably not even allowed) to fill the column 'ref' since it has AUTO_INCREMENT.
Here's the link to MySQL's documentation/function reference about LAST_INSERT_ID().

Foreign Key Failure in MySQL

I have created a database composed of three tables. This is my query in creating my tables with Foreign Key.
CREATE TABLE reporter
(
reporterid INT NOT NULL AUTO_INCREMENT,
firstname VARCHAR(1000) NOT NULL,
lastname VARCHAR(100) NOT NULL,
PRIMARY KEY (reporterid)
);
CREATE TABLE flood
(
floodid INT NOT NULL AUTO_INCREMENT,
address VARCHAR(500) NOT NULL,
description VARCHAR(1000) NOT NULL,
dateofflood DATE NOT NULL,
timeofflood INT NOT NULL,
PRIMARY KEY (floodid)
);
CREATE TABLE reports
(
reportid INT NOT NULL AUTO_INCREMENT,
timereport NODATATYPE NOT NULL,
datereport DATE NOT NULL,
rid INT NOT NULL,
fid INT NOT NULL,
PRIMARY KEY (reportid),
FOREIGN KEY (rid) REFERENCES reporter(reporterid),
FOREIGN KEY (fid) REFERENCES flood(floodid)
);
I created a system in order for me to add records/row on my database through PHP. This is my code:
<?php
mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("flooddatabase")or die("Connection Failed");
$description = $_POST['description'];
$address = $_POST['address']; // Make sure to clean the
$dateofflood=$_POST['dateofflood'];
$timeofflood=$_POST['timeofflood'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$dateofreport=$_POST['dateofreport'];
$timeofreport=$_POST['timeofreport'];
$query = "INSERT into flood(address,description,dateofflood,timeofflood) values ('$address','$description','$dateofflood','$timeofflood')";
$query2 = "INSERT into reporter(firstname,lastname) values ('$firstname','$lastname')";
$query3 = "INSERT into reports(dateofreport,timeofreport) values ('$dateofreport','$timeofreport')";
if(mysql_query($query))
if(mysql_query($query2))
if(mysql_query($query3))
{
echo "";
} else
{
echo "fail";
}
?>
The result that I am getting is fine. It's just that, in my REPORTS table, there is no foreign key that is being generated. For example I input something on my reporter table and flood table, the foreign key 'rid' and 'fid' has no values that references to both tables. Need help thank you.
Get the just inserted Primary key value from flood table insert
query. And store it to a variable say $f_id;
Get the just inserted primary key value from reporter table insert
query and store it to a variable say $r_id;
Now Make your last insert statement like below:
"INSERT into reports(dateofreport,timeofreport,rid,fid) values ('$dateofreport','$timeofreport',$r_id,$f_id)";
I am not giving you a direct copy paste solution.
If you need to know how to get the last inserted id by executing an insert query then look at this link
there is no foreign key that is being generated
I'm not entirely sure what you even mean by that. Foreign keys aren't "generated". Primary keys can be, which you do:
reporterid INT NOT NULL AUTO_INCREMENT
(as well as for your other two tables)
the foreign key 'rid' and 'fid' has no values
Well, look at your query:
INSERT into reports(dateofreport,timeofreport) values ...
Where do you insert values for rid and fid? I'm actually pretty surprised this query works at all, since those columns don't allow NULL values:
rid INT NOT NULL,
fid INT NOT NULL,
(Though your column names also don't line up, so I find it likely that the code you're showing isn't actually the code you're using...) That point aside however, the fact still remains that if you want a value in those fields then you have to put a value in those fields:
INSERT into reports(dateofreport,timeofreport,rid,fid) values ...
After each query, you can get the last generated identifier from mysql_insert_id():
$last_id = mysql_insert_id();
Use that to then populate the values being inserted as foreign keys in subsequent queries.
Also worth noting, the mysql_* libraries are long since deprecated and have been replaced with mysqli_ and other libraries such as PDO. I highly recommend you upgrade to a current technology, since what you're using isn't supported by any vendor.
Additionally, and this is very important, your code is wide open to SQL injection attacks. This basically means that you execute any code your users send you. You should treat user input as values, not as executable code. This is a good place to start reading on the subject, as is this.

INSERT... ON DUPLICATE KEY UPDATE issue

I am having a mysql table named company_profile. It may have only one record. So I tried to insert and update data of the table using INSERT.... ON DUPLICATE KEY UPDATE query.
This is how I tried it:
$sql = "INSERT INTO company_profile (
company_name
, tel
, mobile
, fax
, email
) VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
company_name= VALUES(company_name)
, tel = VALUES(tel)
, mobile = VALUES(mobile)
, fax = VALUES(fax)
, email = VALUES(email)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('sssss', $company_name
, $telephone
, $mobile
, $fax
, $email
);
$stmt->execute();
My problem is when I updating the data, it always inserting a new record into my table.
Can anybody tell me what would be the problem of this?
My table structure looks like this:
CREATE TABLE IF NOT EXISTS company_profile (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
company_name VARCHAR(120) NOT NULL,
tel VARCHAR(20) NOT NULL,
mobile VARCHAR(20) NOT NULL,
fax VARCHAR(20) DEFAULT NULL,
email VARCHAR(60) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
First, it is redundant to define a key as being both unique and primary key. Just define id to be primary key.
Then, you need a unique constraint/index on the columns used for duplication (the two are functionally equivalent for this purpose). I am guessing uniqueness is based on the company name:
create unique index unq_company_profile_company_name on company_profile(company_name);

Problems insert data in database

I made a database recipes, it consists of; recipe's name, ID number, ingredients, preperation, image etc.
After that I made a php and html script so I can search in the databese (for example: dinner with preperation time less than 45 min.).
No I'm working on a php script to insert new recipes. I can insert $sql1. But when I try to insert $sql2 it says:
Could not enter data retval 2: Cannot add or update a child row: a foreign key constraint fails (recepten.benodigdheid, CONSTRAINT benodigdheid_ibfk_1 FOREIGN KEY (ID) REFERENCES gerecht (ID))
I understand the problem is in the child/parent relation and the foreign key, but I can't find the problem. Do you first have to add data in 'Ingredient'? Or first in 'Gerecht'?
Below I wrote down part of the script, I can give more if required.
PHP script to insert new recipe:
$sql1="INSERT INTO Gerecht ( gerechtnaam, personen, categorie, bereidingstijd, bereidingswijze, plaatje)
VALUES ('$gerechtnaam','$personen','$categorie','$bereidingstijd','$bereidingswijze','$plaatje')";
$sql2="INSERT INTO Benodigdheid (benodigdheden)
VALUES ('$benodigdheden')";
$sql3="INSERT INTO Product (ingredientnaam, eenheidnaam)
VALUES ('$ingredientnaam1', '$eenheid1')";
$sql4="INSERT INTO Ingredient (ingredientnaam, hoeveelheid)
VALUES ('$ingredientnaam1', '$hoeveelheid1')";
$retval1 = mysqli_query($db, $sql4 );
if(! $retval1 )
{
die('Could not enter data retval 1: ' . mysqli_error($db));
}
echo "Entered data retval1 successfully\n";
$retval2 = mysqli_query($db, $sql2 );
if(! $retval3 )
{
die('Could not enter data retval 2: ' . mysqli_error($db));
}
echo "Entered data retval2 successfully\n";
Create script database:
CREATE TABLE Gerecht
(ID INT(3) AUTO_INCREMENT NOT NULL,
gerechtnaam VARCHAR(35) NOT NULL,
personen NUMERIC(2) NOT NULL,
categorie VARCHAR(25) NOT NULL,
bereidingstijd NUMERIC(3) NOT NULL,
bereidingswijze TEXT NOT NULL,
plaatje VARCHAR(250) NOT NULL,
PRIMARY KEY (ID)
);
CREATE TABLE Benodigdheid
(ID INT(3) NOT NULL,
benodigdheden VARCHAR(35) NOT NULL,
PRIMARY KEY (ID, benodigdheden),
FOREIGN KEY (ID) REFERENCES Gerecht (ID)
);
CREATE TABLE Eenheid
(eenheidnaam VARCHAR(12) NOT NULL,
PRIMARY KEY (eenheidnaam)
);
CREATE TABLE Product
(ingredientnaam VARCHAR(35) NOT NULL,
eenheidnaam VARCHAR(12),
PRIMARY KEY (ingredientnaam),
FOREIGN KEY (eenheidnaam) REFERENCES Eenheid (eenheidnaam)
);
CREATE TABLE Ingredient
(ID INT(3) NOT NULL,
ingredientnaam VARCHAR(35) NOT NULL,
hoeveelheid NUMERIC(4) NOT NULL,
PRIMARY KEY (ID, ingredientnaam),
FOREIGN KEY (ID) REFERENCES Gerecht (ID),
FOREIGN KEY (ingredientnaam) REFERENCES Product (ingredientnaam)
);
You are not trying to insert the ID of the Gerecht when inserting into Benodigheid. You MUST insert this value as well since there is a referential integrity constraint on the table. After your first SQL insert, you need to read out the id of the last inserted Gerecht record (perhaps by using mysqli_insert_id() and then add that id value in the insert to Benodigheid table. So $sql2 should look like this:
$sql2="INSERT INTO Benodigdheid (ID, benodigdheden)
VALUES ($id_from_sql1, '$benodigdheden')";
Your Benodigdheid table also seems flawed in that it should have its own autoincrement primary key as well as the foreign key referencing Gerecht. Though in looking at what you are doing, it seems like there is 1 to 1 relationship between Gerecht and Benodigheid, so I actually don't know why you wouldn't just have benogdigheid as a column on Gerecht if this is your intent.
I generally looking over your schema, it would seem clear that you need to get in the practice of adding autoincrement primary keys to your tables (which is commonly done for most all relational DB tables). You are going to have the same problem on your ingredient tables
You have set a constraint on the table Benodigdheid from its key ID to the primary key ID in Gerecht. You need a separate foreign key. You can't have the primary key and the foreign key be the same column.
I don't understand the words so I don't know exactly what fits to what, but that constraint is a problem and gives you the error.

Categories