0

How can I check in MYSQL PHP if two columns are unique then not insert again, else if just one column is unique then insert, is that even possible to do in php?

EDIT:

Lets say I have a table like this,

userId  |  codeId

And I I send a query like this,

$query = $pdo->prepare('insert into table (userId, codeId) values (?,?)');

So now I want to check if userId and codeId are added already once do not insert again, and if just one is added, then do insert the entire query,

I hope its more understanding.

2
  • 1
    I don't get it. Could you elaborate more and maybe show examples? A good question makes good answers. Commented Jul 6, 2012 at 14:30
  • I updated, please let me know if that makes sense for you, thanks for your time Commented Jul 6, 2012 at 14:38

3 Answers 3

2

Set up a unique key for those columns, then the mysql query will FAIL when you try to insert.

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

3 Comments

But if when I try to insert the columns and just one column has a duplicated entry and one don't have, I want the query should insert the new one, even one of the columns are duplicated, is that possible to do?
@itsme you can set a unique key for a set of columns. And it will only fail if both are the same.
@itsme I am happy to help ^_^
1

Use REPLACE INTO instead of INSERT INTO ... ?

1 Comment

REPLACE INTO will DELETE and INSERT again, but this is not the desired behavior. The behavior must be: It then duplicate key: UPDATE, else: INSERT.
0

Do something like the code below (where TEXT_ID and TEXT_CATEGORY, are keys of table):

INSERT INTO 
    table_texts
SET 
    text_id = 174,
    text_category = "pam_texto"
ON DUPLICATE KEY UPDATE 
    text_id = 174,
    text_category = "pam_texto";

The above code tries to insert, but if the keys are duplicated performs an update on the line.

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.