Gossamer Forum
Home : General : Databases and SQL :

See if field exists?

Quote Reply
See if field exists?
I know that its just as easy to really easy to just add another SQL: query to check is a certain entry within a table exists, but I was hoping to see if there was a way to see if an entry exists in a specific column when adding something. I.e something you can add to the query, that will stop the addition of it is an identical entry exists.

Could just be wishful thinking here...cois I couldn't find anything about it on mysql.com or other SQL sites Frown

Andy (mod)
andy@ultranerds.co.uk
Want to give me something back for my help? Please see my Amazon Wish List
GLinks ULTRA Package | GLinks ULTRA Package PRO
Links SQL Plugins | Website Design and SEO | UltraNerds | ULTRAGLobals Plugin | Pre-Made Template Sets | FREE GLinks Plugins!
Quote Reply
Re: [Andy.] See if field exists? In reply to
Set a column type to UNIQUE and MySQL will not allow duplicate rows. This is commonly used for session ids and such.

- wil
Quote Reply
Re: [Wil] See if field exists? In reply to
You'll still probably have to do a select or count if you want to display a formatted error otherwise you'll get a yucky duplicate key error.
Quote Reply
Re: [Paul] See if field exists? In reply to
True. But that a choice of personal preference. If you can avoid Perl / your SQL database to do extra work I think you'll save yourself a fraction of a second.

- wil
Quote Reply
Re: [Wil] See if field exists? In reply to
There are a few solutions;

You could totally ignore the errors by not errors checking - bad.

You could use $SIG{__DIE__} and then:

$dbh->do($query) || die DBI->errstr;

...to show a formatted error but with the default error text.

Or you could do the same as above but with some sort of regex or hash setup to show a custom error, which may be messy....eg...

my $keys = { duplicate => 'This field is a duplicate!' };

$error =~ /^duplicate key/i and print $keys->{duplicate};
Quote Reply
Re: [Paul] See if field exists? In reply to
True (again). But there will always be TMTOWTDI.

- wil
Quote Reply
Re: [Paul] See if field exists? In reply to
I think my first suggestion is the most efficent in the scope of the original question.

- wil
Quote Reply
Re: [Wil] See if field exists? In reply to
Yeah sorry I wasn't trying to make out that what you said wasn't appropriate - I was just typing my thoughts....I'm getting like Pugdog Wink