0

I have a table to store client's answers.I want to use one mysql query to insert or update this table. My Table name : questionform_answer and columns > ClientID QuestionID OptionID

Each client can only have one same question id.For example

 ClientID QuestionID OptionID
    1         1         1
    1         2         5
    2         1         3

I want to update OptionID if already exist ClientID and QuestionID.I don't want to use select query so taking so time. I tried

     ON KEY UPDATE
     Replace Into

But I could not. I use php so I tried first update query and if mysqli return fail insert row but it is also slow. MY insert and update code :

   Insert Into questionform_answer (ClientID,QuestionID,OptionID) values 
   ('$ClientID','$soruid','$cevapid')


   Update questionform_answer set OptionID='$cevapid' where 
   ClientID='$ClientID' and QuestionID='$soruid'
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
johnny003
  • 5
  • 7

2 Answers2

0

One way around this is to add a unique key over (ClientID, QuestionID) and use an INSERT ... ON DUPLICATE KEY UPDATE query:

ALTER TABLE table1
ADD UNIQUE INDEX (ClientID, QuestionID);

INSERT INTO table1
VALUES (1, 1, 4)
ON DUPLICATE KEY UPDATE
OptionID = VALUES(OptionID)

Demo on dbfiddle

Nick
  • 138,499
  • 22
  • 57
  • 95
0

First of all, you should use prepared statements to avoid SQL injections. If you have a unique key on (ClientID,QuestionID), you can do INSERT INTO ... ON DUPLICATE KEY like this:

INSERT INTO questionform_answer (ClientID,QuestionID,OptionID) 
            values ('$ClientID','$soruid','$cevapid') 
on duplicate key update OptionID='$cevapid'
nacho
  • 5,280
  • 2
  • 25
  • 34