Welcome Guest, Not a member yet? Register   Sign In
How to insert non-duplicated data on a database?
#1

[eluser]João Ramos[/eluser]
Hello,

I'm a rookie dev and I guess I need help figuring out how to deal with the following situation: I have an array with strings I want to insert into my database, but I only want to insert those who are not yet on the database. How should I do this?

Thanks in advance, guys!
João
#2

[eluser]smilie[/eluser]
Well, the best way would be to make your field unique; this way, MySQL will return error in case you try to enter duplicate entry. Ofcourse, try to check your (insert) code as well, but in this case if you make mistake somewhere then MySQL will still stop it.

But in regard to your PHP code, only thing I can think of is to test (perform select) before you insert it;

Cheers,
Smilie
#3

[eluser]João Ramos[/eluser]
That's quite clever! So I just basically try to insert everything and MySQL will take care of ignoring duplicate contents, right? In case there's an error, will MySQL stop the entire insert query or will just ignore the duplicate contents?

[quote author="smilie" date="1328633922"]Well, the best way would be to make your field unique; this way, MySQL will return error in case you try to enter duplicate entry. Ofcourse, try to check your (insert) code as well, but in this case if you make mistake somewhere then MySQL will still stop it.

But in regard to your PHP code, only thing I can think of is to test (perform select) before you insert it;

Cheers,
Smilie[/quote]
#4

[eluser]Bhashkar Yadav[/eluser]
yes, it will be the best way to make your field unique. to avoid the MYSQL error you can use IGNORE keyword. this will continue the processing to next row.
#5

[eluser]Bhashkar Yadav[/eluser]
please look at http://dev.mysql.com/doc/refman/5.1/en/c...y-key.html
#6

[eluser]smilie[/eluser]
As Bhashkar said, IGNORE should do the trick;
there is 'manual' way, buy catching MySQL error:

#1062 - Duplicate entry 'abc' for key 'name';

This way you can yourself catch this error and if it occurs, just continue the loop.

Cheers,
Smilie
#7

[eluser]João Ramos[/eluser]
Thank you all guys. Best support I could get for my first thread here on CI forums Smile
#8

[eluser]João Ramos[/eluser]
Could you please be explain how to use that IGNORE keyword? Is it something I add to my active record query?

[quote author="Bhashkar" date="1328634518"]yes, it will be the best way to make your field unique. to avoid the MYSQL error you can use IGNORE keyword. this will continue the processing to next row.[/quote]




Theme © iAndrew 2016 - Forum software by © MyBB