0

Hi I've been trying to get this to work, I thought I had it with mysql - INSERT... ON DUPLICATE KEY UPDATE, but no luck.

I have a table as such:

sessionID is unique, productID references another table and is not unique, but not common, should be a max of 3 rows containing the same value, sessionType is either 1, 2 or 3, and would link with productID,

I need to check if the table has a row where there is a matching pair of productID and sessionType, if there is then sessionDate & sessionCapacity in that row should be UPDATED, if there isn't then a new row inserted.

$vals = array($pID,$data['pSessionDate'],'1',$data['pQty'],$pID,$data['pSessionDate'],'1',$data['pQty']);
$db->Execute("INSERT INTO VividStoreSessions (pID,sDate,sType,sCapacity) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE pID=?,sDate=?,sType=?,sCapacity=?",$vals);

Hope that makes sense to someone and thanks in advance for any help!

1

1 Answer 1

2

Your insert looks valid. But, first you need a unique index/constraint:

create unique index unq_VividStoreSessions_productId_sessionType
    on VividStoreSessions, productId, sessionType)

Then you can write the code to only use four parameters:

INSERT INTO VividStoreSessions (pID, sDate, sType, sCapacity)
     VALUES (? ,?, ?, ?)
    ON DUPLICATE KEY UPDATE sDate = VALUES(sDate), Capacity = VALUES(Capacity);

Finally, you need to ensure that sType only takes on the values of 1, 2, or 3. Perhaps you want to enforce this at the application layer. Otherwise, you need a trigger or foreign key constraint to ensure that there are only three rows.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.