Insert row into a table with foreign key inside PHP - php

I am creating a PHP website that use Apache web server (PHPmyAdmin)
I have 3 tables :
brand
brand_id (PRIMARY KEY) AUTO INCREMENT
brand_name
item
item_id (PRIMARY KEY) AUTO INCREMENT
item_category
model
model_id (PRIMARY KEY) AUTO INCREMENT
item_model
brand_id (FOREIGN KEY for brand.brand_id)
brand_name (FOREIGN KEY for item.item_id)
quantity
price
I have a problem when I want to insert new value into model table.
this is PHP Code that I use for inserting
if (isset($_POST['brand_id']));
$brand = ($_POST['brand_id']);
if (isset($_POST['item_id']));
$cat = ($_POST['item_id']);
if (isset($_POST['model']));
$model = ($_POST['model']);
if (isset($_POST['quantity']))
$quantity = ($_POST['quantity']);
if (isset($_POST['price']))
$price = ($_POST['price']);
$sql = "INSERT INTO model (item_model, brand_id, item_id, quantity, price)
VALUES ('$model', '$brand', '$cat', '$quantity', '$price')";
Note that I did not insert any value into the model_id because I think it will automatically increased for it is AUTO increment. I dont know whether I am right or wrong.
the isset values are passed from another PHP file. so this PHP basically just catch the thrown values from previous PHP file.
I had tried to insert value directly from the PHPmyAdmin using SQL statement and it yielded this error :
Cannot add or update a child row: a foreign key
constraint fails (`stock`.`model`, CONSTRAINT `fk_item_brand`
FOREIGN KEY (`brand_id`) REFERENCES `brand` (`brand_id`) ON UPDATE CASCADE)
and if I tried to put in a id value into one of the column, it will yield an error:
SQL query:
INSERT INTO `model`(`model_id`, `item_model`, `brand_id`, `item_id`, `quantity`, `price`)
VALUES (1,'a','1','1','a','a')
MySQL said: Documentation
#1062 - Duplicate entry '1' for key 'PRIMARY'
How do I insert a row into a table with foreign key inside PHP?

$sql = "INSERT INTO model (model_id,item_model, brand_id, item_id, quantity, price)
VALUES (null,'$model', '$brand', '$cat', '$quantity', '$price')";
Try this.
Add auto increment field and pass value null

Related

Can i get the `insert_id` (actually just the `id`) when inserting with `ON DUPLICATE KEY`? [duplicate]

Supposing I have a table:
CREATE TABLE files (
id_prod INT UNSIGNED NOT NULL DEFAULT PRIMARY KEY AUTO_INCREMENT,
id_rel INT UNSIGNED,
name VARCHAR(250),
other VARCHAR(200),
UNIQUE INDEX(id_rel , name)
);
and I want to use an unique query to insert/update the data on this table:
INSERT INTO files (id_rel , name)
VALUES ('25', 'test')
ON DUPLICATE KEY UPDATE
now, reading the MySQL manual I read about this:
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)
so I thought my query should be:
INSERT INTO files (id_rel , name)
VALUES ('25', 'test')
ON DUPLICATE KEY UPDATE id_prod = LAST_INSERT_ID(id), name = 'TESTED'
but which is the difference if I use only:
INSERT INTO files (id_rel , name)
VALUES ('25', 'test')
ON DUPLICATE KEY UPDATE name = 'TESTED'
?
I cannot understand the meaning of LAST_INSERT_ID(id). What is (id) and what it's supposed to do?
This is only necessary if your application needs to call LAST_INSERT_ID() after performing the INSERT. Normally, LAST_INSERT_ID() will only return a value if you actually inserted a new row into the table, not of there was a duplicate key and it updated the row instead.
From the documentation:
If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID().
If you use the idiom you quoted, LAST_INSERT_ID() will return either the ID of the new row that was inserted or the row that was updated.

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

MySql constraint violation. Inserting

I have database with 5 tables
students PK : ID -> anum, first, last
studentinfo PK/FK : ID -> why, student_commenets, finished, aidyear
Times PK/FK : ID -> signintime, counselor_start_time,
additional_time, finish_time
counselor PK/FK : ID -> firstcounselor, secondcounselor, thirdcounselor
Comments PK/FK : ID -> counselorcomments, additional_commenets
I have a page called signinpage.php
on that page I have to write to three different tables (student, studentinfo, and time)
My code is as fallows :
if (empty($errors) === true)
{
include('core/queries/inserts.updates.selects/students.php');
include('core/queries/inserts.updates.selects/studentinfo.php');
include('core/queries/inserts.updates.selects/signintime.php');
$dbh = null;
header('location: signedin.php');
exit();
}
each of the files are actual insert queries. (if you yall need to see them I will update this post)
The error I am having is :
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails (test.times,
CONSTRAINT times_ibfk_2 FOREIGN KEY (id) REFERENCES students
(id) ON DELETE CASCADE ON UPDATE CASCADE)
To add on to this, the first query (the students.php and the second query studentinfo.php)
are inserting just fine. Same ID, the problem occurs with the signintime inserting into table : times.
In phpmyadmin both tables (studentinfo and times) are configured alike with both have cascade on delete and update to the original table (student) since the student him/her starts the session (which is the PK ID).
How can I solved this error?
Edit :
<?php
require('core/init.php');
try
{
$null = NULL;
$query = $dbh->prepare("INSERT INTO `times` (signintime) VALUES (:signintime)");
$query->bindParam(':signintime' , $null);
$query->execute();
}
catch (PDOException $e)
{
error_log($e->getMessage());
die($e->getMessage());
}
?>
Your table design looks wrong to me. I'm assuming there can be multiple entries in the times table for each row in the students table. In that case, you would need the following columns in times:
id - PK
student_id - FK
signintime
counselor_start_time
additional_time
finish_time
Then each row for a particular student would have the same student_id value, but different id values.
The following statements and example is different from the tables you have mentioned but the thought is still the same.
The reason why the error was generated is because you are trying to insert a value on a child table in which that value is not yet present on the parent table. The child table means that it is dependent on the other table (which is the Parent).
To explain further, consider the following schema,
CREATE TABLE StudentList
(
ID INT PRIMARY KEY,
NAme VARCHAR(50)
);
CREATE TABLE AddressList
(
StudentID INT,
Address VARCHAR(50),
CONSTRAINT tb_fk FOREIGN KEY (StudentID)
REFERENCES StudentList(ID)
);
INSERT INTO StudentList VALUES (1, 'Jon');
INSERT INTO StudentList VALUES (2, 'Skeet');
INSERT INTO AddressList VALUES (1, 'Hello');
INSERT INTO AddressList VALUES (2, 'World');
INSERT INTO AddressList VALUES (1, 'Other Address');
There are two tables: StudentList and AddressList. The table Address is the child table and which is dependent to table StudentList (also called the Parent table). The only values that are allowed to be inserted on column StudentID of table AddressList is only 1 and 2 because those are the only IDs found on table StudentList.
When you try to insert record with ID other than 1 and 2 on table Address, eg
INSERT INTO AddressList VALUES (1, 'Other Address');
it will generate an error telling that:
Cannot add or update a child row: a foreign key constraint fails
(db_2_ec2e8.addresslist, CONSTRAINT tb_fk FOREIGN KEY
(StudentID) REFERENCES studentlist (ID)):
because the value of the column StudentID being inserted on the table is not available on the parent table (StudentList).
So, I hoped that this will help you understand now.
SQLFiddle Demo

Add a unique key to database

I've got a form on my website for users to input their fname, sname, company,phone,email which then gets updated to a database on submit. I also have a field in my database for a unique userID to incase users have same name and company ect. When submitting my form how is it possible to add in this field, a unique number so that it is +1 from the fields taken already. At the minute there are only 3 userIDs so i need the next inputted one to be 4 and so on.
At the moment I have this.
require_once('dbConnect.php');
//taken from a smarty template form.
$addForename = $_POST['forename'];
$addSurname = $_POST['surname'];
$addCompany = $_POST['company'];
$addContact = $_POST['contact'];
$addEmail = $_POST['email'];
public function addUser($addForename,$addSurname,$addCompany,$addContact,$addEmail)
{
$sql = "INSERT INTO `Users` (`Forename`, `Surname`, `ComanyName`, `Phone`, `Email`) VALUES ('".$addForename."','".$addSurname."','".$addCompany."','".$addContact."','".$addEmail."')";
$databaseAccess = new DatabaseConnect();
try
{
$result = $databaseAccess->connect($sql, "add");
}
catch (Exception $e)
{
throw new Exception("Adding User Failed !!!");
}
if ($result)
{
return 1;
}
else{return 0;}
}
thanks
If you are using phpmyadmin there should be a checkbox when youre creating a new column with "A_I" or Auto_Increment.. you have to check that and then it will count your entrys.
Create the row as an auto_increment in the database:
create table someName (ID int primary key auto_increment, col1 int ...);
Then when you are inserting data, either pass it a null, or don't insert that field like this:
insert into someName (col1) values (3);
or
insert into someName (ID, col1) values (null, 3);
You can modify your current table with the following:
ALTER TABLE someName MODIFY COLUMN ID INT NOT NULL AUTO_INCREMENT , ADD PRIMARY KEY (ID);
create the ID:
ALTER TABLE users ADD ID INT UNSIGNED
NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (ID);
and start the auto-increment where you want
ALTER TABLE tbl AUTO_INCREMENT = 4;
Create a column set it as a primary key and auto increment. You can even write a stored procedure for inserting in the table. That way you don't have to write query every time and not have to worry about escape characters. If you want the particular no to be returned from stored procedure use SCOPE_IDENTITY() in the stored procedure.

Categories