Forum Moderators: coopster

Message Too Old, No Replies

Check for existing entry for INSERT

Is there a better/shorter way?

         

AlexLee

2:22 pm on Feb 7, 2005 (gmt 0)

10+ Year Member



Hi, I am currently trying to INSERT some data into MySQL database.

What would be the correct way for checking if an entry of the same name already exist in the primary key.

I was planning to do it like this...

SELECT name FROM table WHERE name = 'whatever'

Do a loop. If data is returned, prompt user that entry exist.

Else, continue to INSERT.

Is this the correct way to do it? Is there a shorter way? And It is alright if I execute a lot of SQL query at one go right? What should I watch out for?

dreamcatcher

4:13 pm on Feb 7, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi,

Well, as you probably know, if you try and insert something into a primary key that already exists you will get an error saying 'Duplicate Entry for Key 1' or something like that.

What you can do is do the insert and then use an if statement to see if the query was ok. Like this:

$query = mysql_query("INSERT INTO table (field) VALUES ('something')") or die(mysql_error());

if ($query)
{

//everything was ok

}
else
{

//oops, not ok

}

dc

Sanenet

4:33 pm on Feb 7, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you're looking for something that's always the same (ie email, telephone, etc) try:

SELECT COUNT(email) AS counter FROM table WHERE email = '{form.email}'

IF email.recordsreturned > '0'
-return to user, record exists!
else
-ADD RECORD SQL
endif

Unless you're really hitting a lot of sequential signups / db usage, you should be fine.