Can't insert values to foreign key attribute in php - php

These are my tables:
create table sender(
sno varchar(6) not null,
sfname varchar(15) not null,
slname varchar(10) not null,
sphone varchar(10),
saddress varchar(40) not null,
constraint pk_sender primary key(sno)
);
create table courier(
cno varchar(6),
cost double precision not null,
weight double precision not null,
del_stat varchar(20) not null,
no_cour int(10),
sno varchar(6),
constraint fk_courier foreign key(sno)
references sender(sno),constraint pk_courier primary key(cno)
);
And this is my php code:
<?php
session_start();
$_SESSION['x']=$_POST[sno];
$con=mysqli_connect("localhost","root","project123","project");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1="insert into sender(sno,sfname,slname,sphone,saddress) values (concat('SN','$_POST[sno]'),'$_POST[sf]','$_POST[sl]','$_POST[sph]','$_POST[sad]')";
$sql2="insert into courier(cno,cost,weight,del_stat,no_cour) values (concat('CN','$_POST[cno]'),'$_POST[cst]','$_POST[wght]','$_POST[del]','$_POST[num]')";
if(!mysqli_query($con,$sql1) && !mysqli_query($con,$sql2))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
But I'm getting error
Error: Cannot add or update a child row: a foreign key constraint fails (project.courier, CONSTRAINT fk_courier FOREIGN KEY (sno) REFERENCES sender (sno))
So please tell me how to insert values to foreign key.

It seems that you're not setting the foreign key value on your child table insert. Your courier table have a column sno VARCHAR(6) that references sender.sno VARCHAR(6) right? So you have to provide it value. In order to relate two fields as foreign key, you have to set a valid value for the child column existing on the parent related column.
Anyway, you should run those two queries like this:
$sno = "SN$_POST[sno]";
$cno = "CN$_POST[cno]";
$sql1="insert into sender(sno,sfname,slname,sphone,saddress) values ('$sno','$_POST[sf]','$_POST[sl]','$_POST[sph]','$_POST[sad]')";
if(mysqli_query($con,$sql1))
{
$sql2="insert into courier(cno,cost,weight,del_stat,no_cour, sno) values ('$cno','$_POST[cst]','$_POST[wght]','$_POST[del]','$_POST[num]', '$sno')";
if (mysqli_query($con,$sql2))
{
// Success
}
else
{
die('Error on query 2: ' . mysqli_error($con));
}
}
else
{
die('Error on query 1: ' . mysqli_error($con));
}
You can see here how to get the last inserted id from an auto_increment field. If you're not using an auto_increment field, you have to select it in other way that fits your needs.
I hope this helps.
UPDATE: I have change those variables sno and cno because you can avoid concatenating it inside your query. You can do that that way. I realize that you already have the sno value, so you don't need to query again after it. That code may now work.

Related

MYSQL Duplicate rows

I am trying to insert values into a table in MYSQL, the table has a column which should be unique,so that column always will have different values.
I tried putting UNIQUE for the coloumn but it did not work,
Also tried putting that column as PRIMARY KEY and insert IGNORE INTO command it did not work (http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm)
My intention is to put phonenumber column unique so every value in this column is different. if the newly inserting value is not unique it should skip wihout giving error.
My code to Create table:
public function create_member_table($table)
{
$this->sql ="CREATE TABLE IF NOT EXISTS $table ( id BIGINT NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
phonenumber VARCHAR(20) NOT NULL,
country VARCHAR(2) NOT NULL,
profession VARCHAR(5000) NOT NULL,
profilepic VARCHAR(5000) NOT NULL,
smskey VARCHAR(100) NOT NULL,
status INT NOT NULL,
reg_date_time DATETIME NOT NULL,
UNIQUE (id,phonenumber))
PARTITION BY HASH(id)
PARTITIONS 1023;";
$this->tb = mysqli_query($this->ret,$this->sql);
if(!$this->tb){
echo "Table not created<br>";
}
else{
echo "Table created<br>";
}
Insert table:
public function table_member_insert($table,$phonenumber="",$username="",$country="",$profession="",$profilepic="0",$smskey="",$status="") {
$this->sql = "INSERT INTO $table
(username,phonenumber,country,profession,profilepic,smskey,status,reg_date_time)
VALUES
('$username','$phonenumber','$country','$profession','$profilepic','$smskey','$status',now());";
$this->tb = mysqli_query($this->ret,$this->sql);
if(!$this->tb){
echo "values not inserted<br>";
}
else{
echo "values inserted<br>";
} }
The problem is that you defined the combination of id and phonenumber fields as unique. Since your id field is defined as auto_increment, it will be unique on its own, therefore any combination with phonenumber field will also be unique.
You need to define the phonenumber field alone as unique. After that you can use insert ignore to insert a new record with an existing phone number without raisin an error. However, pls note that in case of a match, the unique index will prevent the entire record from being inserted.

MySQL CREATE produces redundant index

When creating a new database table with the following code phpMyAdmin reports a redundant index like explained in this post. Is there a way to avoid this behavior and have only one index produced on table creation? I could remove the second index with ALTER TABLE mytest DROP INDEX id; but maybe there is a more elegant solution?
<?php
$sql = "CREATE TABLE IF NOT EXISTS `mytest` (
`id` SERIAL PRIMARY KEY,
`mytext` TEXT
) CHARSET=utf8";
mysqli_query($mysqli, $sql);
$sql = "SHOW INDEX FROM `mytest`";
if ($res = mysqli_query($mysqli, $sql)) {
while ($ds = mysqli_fetch_array($res)) {
echo "<pre>";
print_r($ds);
echo "</pre>";
}
} else echo mysqli_error($mysqli);
?>
According to the documentation:
SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE.
Hence, your declaration is:
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE PRIMARY KEY
So, you are getting an index for UNIQUE and an index for PRIMARY KEY.
The simple solution is to not use "abbreviations" and be clear about what you want:
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY

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.

Joining 2 tables with user input

Alright I have the foreign keys set up and I'm able to join the tables via the sql tab in phpmyadmin, but I can't figure out how to get things to work properly when I allow a user to input the values via a form. Right now I'm just playing around with a very basic form that allows first name, last name, and phone number. First and Last name get sent to a table named Customer and phone number gets passed to a table called Customer_Number. The problem is that now when I enter values into the input fields, First and Last name saved to the DB table, but phone number doesn't save and spits out this error message Cannot add or update a child row: a foreign key constraint fails (``.Customer_Number, CONSTRAINT Customer_Number_ibfk_1 FOREIGN KEY (Customer_ID) REFERENCES Customer (Customer_ID))
Is there a way I can just add these values and the foreign key for my Customer_Number table update according to the correct customer?
Here is my code:
<?php
$con=mysqli_connect("");
if(mysqli_connect_errno()){
echo "There was a mistake connecting". mysqli_connect_errno();
}
$First=mysqli_real_escape_string($con,$_POST["FirstName"]);
$Last=mysqli_real_escape_string($con, $_POST["LastName"]);
if(!empty($_POST["FirstName"]) && !empty($_POST["LastName"])){
$sql="INSERT INTO Customer(First,Last)
VALUE('$First', '$Last')";
if(!mysqli_query($con,$sql)) {
die("ERROR". mysqli_error($con));
}else{
echo"record added";
}
}
mysql_close($con);
?>
<?php
$con=mysqli_connect("");
if(mysqli_connect_errno()){
echo "There was a mistake connecting". mysqli_connect_errno();
}
$Phone=mysqli_real_escape_string($con,$_POST["Number"]);
if(!empty($_POST["Number"])){
$sql="INSERT INTO Customer_Number(Number)
VALUE('$Phone')";
if(!mysqli_query($con,$sql)) {
die("ERROR". mysqli_error($con));
}else{
echo"record added";
}
}
mysql_close($con);
?>
And here is my table information:
CREATE TABLE `Customer` (
`Customer_ID` int(11) NOT NULL AUTO_INCREMENT,
`First` varchar(255) NOT NULL,
`Last` varchar(255) NOT NULL,
PRIMARY KEY (`Customer_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
CREATE TABLE `Customer_Number` (
`Num_ID` int(11) NOT NULL AUTO_INCREMENT,
`Customer_ID` int(11) NOT NULL,
`Number` varchar(255) NOT NULL,
PRIMARY KEY (`Num_ID`),
KEY `Customer_ID` (`Customer_ID`),
CONSTRAINT `Customer_Number_ibfk_1` FOREIGN KEY (`Customer_ID`) REFERENCES `Customer` (`Customer_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
I know there has got to be a way to do this, but I'm new to this and my google searches has only really covered how to do this via phpMyAdmin and manually entering in the foreign key values.
Since Customer_Number.Customer_ID is a foreign key pointing to the corresponding Customer row, you need to set Customer_Number.Customer_ID to the correct value when inserting the number after inserting the Customer.
As long as you're using the same connection (ie skip closing/reopening it between the queries), you can use LAST_INSERT_ID() to get the Customer_ID of the just inserted customer, something like (the SQL part only);
INSERT INTO Customer(First,Last)
VALUES ('$First', '$Last')
INSERT INTO Customer_Number(Customer_ID, Number)
VALUES (LAST_INSERT_ID(), '$Phone')

Trying to update two tables at once MySQL

I've been trying make my database work so that cuisineid columns in different tables are linked together. I've got as far as defining the Primary and Foreign Keys on the two tables but when I try and update them now I get this error:
Insert failed: Cannot add or update a child row: a foreign key constraint fails
(`ml11maj_Databasetest`.`Nation`, CONSTRAINT `Foreign Key` FOREIGN KEY (`cuisineid`)
REFERENCES `recipename` (`cuisineid`) ON DELETE CASCADE ON UPDATE CASCADE)
The rest of the upload works, but nothing is added into the Nation(cuisine id is the primary key and currently set to AI) table, the code to insert currently looks like this
if ($cuisine !=''){
$query = "INSERT INTO`Nation`(cuisine_type)VALUES('$cuisine')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
}
EDIT
Nation Table Contains two columns
-Cuisine_type Varchar
-cuisineid int Primary
The recipename table
-recipeid int(255) AUTO_INCREMENT
-mealname text
-b_l_d varchar(30)
-ingredients text
-hours int(11)
-minutes int(11)
-recipe text utf8_bin
-feeds int(11)
-imagepath varchar(100)
-userid int(11)
-cuisineid int(255)
Your insert does not have a cuisine_id, so the foreign key constraint fails, as it tells you. If you want that column to be NULLABLE then you can omit the cuisine_id column in your insert.

Categories