I am using a three table structure to deal with a many-to-many relationship. I have one table that has a list of people and another that has a list of items. Sometimes multiple people have the same item and sometimes multiples items are linked to the same person so I set up the following table structure:
CREATE TABLE people (
id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
fname varchar(128) NOT NULL,
lname varchar(128) NOT NULL,
);
CREATE TABLE items (
id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
name varchar(128) NOT NULL UNIQUE,
);
The UNIQUE prevents the item name from repeating.
CREATE TABLE people_items (
pid int(11) NOT NULL,
iid int(11) NOT NULL,
FOREIGN KEY (pid) REFERENCES people(id)
ON UPDATE CASCADE
ON DELETE CASCADE
FOREIGN KEY (iid) REFERENCES items(id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
This allows me to link multiple items to multiple people and vice versa. It also allows me to delete unnecessary records from the intermediate table.
All works fine so long as a new item is entered, but if an existing item is entered, the intermediate table is not updated, even though the people table is. I also do not get any errors.
Items are a comma delimited text entry which are exploded and lower cased into $items.
First I insert any new items and retrieve the id:
for ($i=0;$i<count($items);$i++){
$sql="INSERT IGNORE INTO items (name) VALUES (?);";
$stmt=$conn->prepare($sql);
$stmt->bind_param('s',$items[$i]);
$stmt->execute();
$itemid=$stmt->insert_id;
If a new id is returned the following is executed:
if ($itemid){
$sql="INSERT INTO people_items (pid,iid) VALUES (?,?);";
$stmt=$conn->prepare($sql);
$stmt->bind_param('ii',$peopleid,$itemid);//the $peopleid is acquired the same way that the $itemid is acquired above
$stmt->execute();
}
Up to here, everything works just fine. At this point if an existing item is already in the items table, is where my intermediate table does not update. The people table however updates just fine, and the items table does not need to update as it already has the item in it.
Here is where I tried two different approaches to update the intermediate table.
First I kept the select and insert queries separate.
elseif(!$itemid){
$sql="SELECT id,name FROM items WHERE name=?;";
$stmt=$conn->prepare($sql);
$stmt->bind_param('s',$items[$i]);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($iid,$name);
$stmt->fetch();
$sql="INSERT INTO people_items (pid,iid) VALUES (?,?);";
$stmt=$conn->prepare($sql);
$stmt->bind_param('ii',$pid,$iid);
$stmt->execute();
}
Here is my alternative approach which also does not update the intermediate table:
elseif(!$itemid){
$sql="INSERT INTO people_items (pid, iid) SELECT id,name FROM items WHERE name IN (?);";
$stmt=$conn->prepare($sql);
$stmt->bind_param('s',$items[$i]);
$stmt->execute();
}
What am I doing wrong?
It's because you are using INSERT IGNORE, so if the item already exists, it won't insert anything, and you will get either 0 or the ID of the last successful insert as the ID (per the docs). So what you need to check is the affected number of rows. If it's 0, then it was ignored and you can SELECT it from the DB. If it's not 0, then you can safely insert the last ID.
for ($i=0;$i<count($items);$i++){
$sql="INSERT IGNORE INTO items (name) VALUES (?);";
$stmt=$conn->prepare($sql);
$stmt->bind_param('s',$items[$i]);
$stmt->execute();
$itemid=$stmt->insert_id;
$affected_rows = $stmt->affected_rows;
if ($affected_rows !== 0) {
// insert
}
else {
// select and insert
}
}
Sidenote:
The way you are inserting the items in a loop is terrible for performance, especially if the DB is not in the same host as the server (think of going to the supermarket: do you go N times and get each item by itself, or do you just go once and get your N items?). What you should be doing, is inserting all of the elements in one query. Clearly it's not that clear cut in your case since you the IDs and what not, but you can read about this here to get started.
Sorry I didn't get to this sooner, but I have figured it out and was busy with work in the meantime. I figure I'd provide the answer in case anyone has the same issue in the future. Anyway, the issue was with my SQL query.
Where I had this:
elseif(!$itemid){
$sql="INSERT INTO people_items (pid, iid) SELECT id,name FROM items WHERE name IN (?);";
$stmt=$conn->prepare($sql);
$stmt->bind_param('s',$items[$i]);
$stmt->execute();
}
I should have had this:
elseif(!$itemid){
$sql="INSERT INTO people_items (pid,iid) VALUES (?,(SELECT id FROM items WHERE name IN (?)));";
$stmt=$conn->prepare($sql);
$stmt->bind_param('ss',$peopleid,$items[$i]);
$stmt->execute();
}
Related
I have a statement that looks like this:
$count=0;
while($row = pg_fetch_assoc($result)){
$sql=("INSERT INTO joblist (job_no, billed, completed, paid, paid_amount, inv_no, invoice, type, o_submitted, approval_date, gals, jobtype, name, state, region, territory)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE
job_no=VALUES(job_no), billed=VALUES(billed),completed=VALUES(completed), paid=VALUES(paid), paid_amount=VALUES(paid_amount), inv_no=VALUES(inv_no), invoice=VALUES(invoice), type=VALUES(type), o_submitted=VALUES(o_submitted), approval_date=VALUES(approval_date), gals=VALUES(gals), jobtype=VALUES(jobtype), name=VALUES(name), state=VALUES(state), region=VALUES(region), territory=VALUES(territory)");
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssssssssssssss",$job_no, $billed, $completed, $paid, $paid_amount, $inv_no, $invoice, $type, $o_submitted, $approval_date, $gals, $jobtype, $name, $state, $region, $territory);
$stmt->execute();
$count++;
}
The problem is, I cannot decipher between updated rows and inserted rows. Is there a way I can do this?
I know i can use the effected rows function, but it reads the same if updated/inserted. Any ideas? thanks!
You're looking for an UPSERT with a RETURNING clause.
Taking into account the following table a records ..
CREATE TEMPORARY TABLE t
(id INT PRIMARY KEY, name TEXT);
INSERT INTO t VALUES (1,'elgar'),(2,'bach'),(3,'brahms');
.. you can use an UPSERT to catch a primary key conflict and ask the query to return the affected records. You can put this insert inside a CTE and count it with a new query. The following query will insert two already existing primary keys (1 and 2) and a new one (4):
WITH j (affected_rows) AS (
INSERT INTO t VALUES (1,'edward'),(2,'johann sebastian'),(4,'schubert')
ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name
RETURNING *
) SELECT count(affected_rows) FROM j;
count
-------
3
See the results yourself :-)
SELECT * FROM t ORDER BY id;
id | name
----+------------------
1 | edward
2 | johann sebastian
3 | brahms
4 | telemann
I want to use one form to insert into two different Microsoft sql tables. I tryed to use 2 inserts, but didnt work.
if (isset($_GET['submit'])) {
$sth = $connection->prepare("INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter','$Datum','$Verbleib','$DUTNr')");
echo "INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter',$Datum,'$Verbleib','$DUTNr')";
$sth->execute();
if($sth)
{
echo "";
}
else
{
echo sqlsrv_errors();
}
$MID = $connection->prepare("MAX(MID) as MID FROM DB.dbo.Fehler WHERE DB.dbo.Fehler.TestaufstellungID = '". $TestaufstellungID . "'");
$MID->execute();
$sth2 = $connection->prepare("INSERT INTO DB.dbo.Fehlerinfo (MID, Tester, Test, Ausfallbedingungen, Fehlerbeschreibung, Ersteller) VALUES ($MID, '$Tester','$Test','$Ausfallbedingungen','$Fehlerbeschreibung','$Ersteller')");
$sth2->execute();
To understand MID is the Primary key of table Fehler and ist the foreign key in the second table Fehlerinfo
Thats why i have the select work around to get the last MID and want to save it in a variable $MID to insert it into the second table.
Is there a smarter solution possible?
As I mentioned in the comments, generally the better way is to do the insert in one batch. This is very over simplified, however, should put you in the right direction. Normally you would likely be passing the values for the Foreign Table in a Table Value Parameter (due to the Many to One relationship) and would encapsulate the entire thing in a TRY...CATCH and possibly a stored procedure.
I can't write this in PHP, as my knowledge of it is rudimentary, but this should get you on the right path to understanding:
USE Sandbox;
--Couple of sample tables
CREATE TABLE dbo.PrimaryTable (SomeID int IDENTITY(1,1),
SomeString varchar(10),
CONSTRAINT PK_PTID PRIMARY KEY NONCLUSTERED (SomeID));
CREATE TABLE dbo.ForeignTable (AnotherID int IDENTITY(1,1),
ForeignID int,
AnotherString varchar(10),
CONSTRAINT PK_FTID PRIMARY KEY NONCLUSTERED(AnotherID),
CONSTRAINT FK_FTPT FOREIGN KEY (ForeignID)
REFERENCES dbo.PrimaryTable(SomeID));
GO
--single batch example
--Declare input parameters and give some values
--These would be the values coming from your application
DECLARE #SomeString varchar(10) = 'abc',
#AnotherString varchar(10) = 'def';
--Create a temp table or variable for the output of the ID
DECLARE #ID table (ID int);
--Insert the data and get the ID at the same time:
INSERT INTO dbo.PrimaryTable (SomeString)
OUTPUT inserted.SomeID
INTO #ID
SELECT #SomeString;
--#ID now has the inserted ID(s)
--Use it to insert into the other table
INSERT INTO dbo.ForeignTable (ForeignID,AnotherString)
SELECT ID,
#AnotherString
FROM #ID;
GO
--Check the data:
SELECT *
FROM dbo.PrimaryTable PT
JOIN dbo.ForeignTable FT ON PT.SomeID = FT.ForeignID;
GO
--Clean up
DROP TABLE dbo.ForeignTable;
DROP TABLE dbo.PrimaryTable;
As i mentioned the answer how it works for me fine atm.
if (isset($_GET['submit'])) {
$failInsert = ("INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter','$Datum','$Verbleib','$DUTNr')");
$failInsert .= ("INSERT INTO DB.dbo.Fehlerinfo (MID, Tester, Test, Ausfallbedingungen, Fehlerbeschreibung, Ersteller) VALUES (NULL, '$Tester','$Test','$Ausfallbedingungen','$Fehlerbeschreibung','$Ersteller')");
$failInsert .= ("UPDATE DB.dbo.Fehlerinfo SET DB.dbo.Fehlerinfo.MID = i.MID FROM (SELECT MAX(MID)as MID FROM DB.dbo.Fehler) i WHERE DB.dbo.Fehlerinfo.TestID = ( SELECT MAX(TestID) as TestID FROM DB.dbo.Fehlerinfo)");
$sth = $connection->prepare($failInsert);
$sth->execute();
}
After looking around on stackoverflow, I'm still having a little trouble understanding the one-to-many relationship in mysql. I have a request coming in from the user (form submission) which will be stored in one table. This is a dynamic form that lets the user add extra fields therefore those will be stored in a separate table. So in short, in my db design, there will be one table for the users with PRIMARY KEY AUTO INCREMENT and there will be another table for the hostnames PER user (multiple fields -array) and using a foreign key that references to the primary key in the user table. Sorry if this is long but trying to make this a good question.
Example:
User Table: (ONE)
1. John Doe, blah, 11-12-15
2. Sally Po, blah, 11-14-15
3. John Doe, blah, 11-15-15
(these are three separate requests)
(numbers are primary key auto incr.)
Host Name Table: (MANY)
1. www.johndoe.com
1. www.johndoe2.com
1. www.johndoe3.com
2. www.sallypo.com
2. www.sallypo2.com
(these numbers (foreign key) should match the primary key for each request)
Code (Leaving out the actual queries + pretty sure I shouln't be using last_id):
$sql = "CREATE TABLE IF NOT EXISTS userTable (
id int AUTO_INCREMENT,
firstName VARCHAR(30) NOT NULL,
date DATE NOT NULL,
PRIMARY KEY (id)
)";
//query
$sql = "CREATE TABLE IF NOT EXISTS hostNamesTable (
id int NOT NULL,
hostName VARCHAR(90) NOT NULL,
FOREIGN KEY (id) REFERENCES userTable(id)
)";
//query
$sql = "INSERT INTO userTable (firstName, date)
VALUES ('$firstName', '$date')";
//query
$last_id = mysqli_insert_id();
for($i = 0; $i < sizeof($hostName); $i++){
$sql = "INSERT INTO hostNamesTable (id, hostName)
VALUES ('$last_id', '$hostName[$i]')";
//query
}
What am I doing wrong? (is this the right way to go about it?)
note: I was trying to get the last_id of the user Table so that I can use it in the hostName table as the foreign key
EDIT: I'm using MySQLi with php
EDIT 2:
After the changes, this is the error I am getting now: Cannot add or update a child row: a foreign key constraint fails (d9832482827984hb28397429.hostNamesTable, CONSTRAINT hostNamesTable_ibfk_1 FOREIGN KEY (id) REFERENCES userTable (id))Error: INSERT INTO hostNamesTable (id, hostName, ) VALUES ('', 'secondhost.net')
--Looks like the $last_id isn't even being recorded?
EDIT 3: Started working. Not sure what it was but I think it was because of some type.
why dont you just add an extra column in the hostNames table which is called "ref_user" and contains the ID of the user you are reffering to? So you can use unique IDs in both tables.
Make a query like:
SELECT * FROM hostNames WHERE ref_user = (SELECT id FROM userTable WHERE <uniqueColumn> = <uniqueIdentifierOfUser>);
But the included request must return only one line from users.
try adding mysqli $link as a parameter in your mysqli_insert_id
$last_id = mysqli_insert_id($link);
i presume you have this somewhere in your code
$link = mysqli_connect("localhost", "mysql_user", "mysql_password", "mysql_db");
if this doesn't work, try using mysql LAST_INSERT_ID() function
$last_id = $mysqli->query("SELECT LAST_INSERT_ID() AS last_id")->fetch_object()->last_id;
I have a form to edit a record (specimen). On the form is a multiple select list which contains records from a table (topic). This select list shows topics as selected that exist for the specimen (as identified in the specimen_topic lookup table) as well as those that can be added to the specimen (from the topic table).
I want to be able to add topics not selected in the list to the lookup table where the topic_fk does not already exist for the specimen_fk:
CREATE TABLE IF NOT EXISTS `specimen_topic_lookup` (
`specimen_topic_lookup_pk` int(6) NOT NULL AUTO_INCREMENT,
`specimen_fk` int(6) NOT NULL,
`topic_fk` int(3) NOT NULL,
PRIMARY KEY (`specimen_topic_lookup_pk`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci AUTO_INCREMENT=8 ;
Any ideas how I can do this?
UPDATE
I have made the fields specimen_fk and topic_fk UNIQUE. Using the code below, only one record is created in specimen_table lookup, when two records should have been created (before making the fields UNIQUE, two records were created OK...). I assume this is because $specimen_pk is the same value for each insert.
foreach($topics as $topic){
$query_topics = "INSERT IGNORE INTO specimen_topic_lookup(specimen_fk, topic_fk)
VALUES ('$specimen_pk', '$topic')";
$result_topics = mysql_query($query_topics, $connection) or die(mysql_error());
}
Looks like having UNIQUE is stopping having a record made with the same value (which is at least what I expected...)
THIS WORKS
Without having to make specimen_fk OR topic_fk UNIQUE...
foreach($topics as $topic){
$query_topics = "INSERT INTO specimen_topic_lookup(specimen_fk, topic_fk)
SELECT '$specimen_pk', '$topic'
FROM DUAL
WHERE NOT EXISTS (SELECT 1
FROM specimen_topic_lookup
WHERE specimen_fk = '$specimen_pk' AND topic_fk = '$topic')";
$result_topics = mysql_query($query_topics, $connection) or die(mysql_error());
Create a unique index on the table and use insert ignore or on duplicate key update:
create unique index specimen_topic_lookup(specimen_fk, topic_fk);
insert ignore into specimen_topic_lookup(specimen_fk, topic_fk)
select $speciment_fk, $topic_fk;
Or, alternatively, you can just do the following without the unique index:
insert into specimen_topic_lookup(specifmen_fk, topic_fk)
select $speciment_fk, $topic_fk
from dual
where not exists (select 1
from specimen_topic_lookup
where specimen_fk = $specimen_fk and topic_fk = $topic_fk
);
Use an INSERT IGNORE statement. This will insert any rows that do not violate the unique key, and ignore the ones that do.
I have this PHP/MySQL script which adds a comment into my DB:
$SQL = "INSERT INTO blog_comments (article_id, author_name, comment, path, posted, status) ";
$SQL .= "VALUES (:article_id, :name, :comment, :next_path, Now(), 'Live');";
$STH = $DBH->prepare($SQL);
$STH->bindParam(':article_id', $article_id);
$STH->bindParam(':name', $name);
$STH->bindParam(':comment', $comment);
$STH->bindParam(':next_path', $next_path);
$STH->execute();
Is there any way to modify this so that it doesn't insert the same [author_name], [article_id] and [comment] into this table? I know it's possible for one column by adding UNIQUE to my table, but not sure about multiple columns.
you can add a UNIQUE constraint for multiple columns
CREATE TABLE
(
.....
CONSTRAINT tab_uq UNIQUE (author_name, comment)
)
or by altering the existing table,
ALTER TABLE myTable ADD UNIQUE (author_name, comment);
call those columns as composite primary key..
that way, they will have a unique entry.
You can make a unique key of multiple fields
I guess you could check the db for a result before inserting data
you can also check INSERT ... ON DUPLICATE KEY UPDATE dev.mysql.com