Jump to content

PHP/Postgresql and EXISTS function


rhyspaterson

Recommended Posts

Hey guys,

 

I'm trying to put together an INSERT command wherein a person can submit a record into the database through a HTML form. However i want to make sure the data is not already in there (stopping duplicates). The table has four columns;

 

id, extension, description and filetype_group

 

I want to match my variable $fileExtension (which is the $_POST variable from the form) against everything in the 'extension' column.

 

So far i have come up with this:

 

$result = pg_exec ($dbconn, "INSERT into filetype (id, extension, description, filetype_group) VALUES ($fileID,'$fileExtension','$fileDescription','$fileGroup') WHERE not exists (SELECT * FROM filetype WHERE filetype.extension = $fileExtension);");

 

 

The code works fine up until the WHERE not exists section, where i get syntax errors, but unfortunately i have no idea what's wrong. I was hoping you guys could shed some light. Primary key for 'filetype' table is the 'id' column.

 

Cheers,

/Rhys

Link to comment
Share on other sites

Hi,

 

You can't do it in one statement.  Instead, do a select to see if it exists, followed by an insert.  If you want to be safe against concurrent inserts, then do it like this:

 

BEGIN

SELECT ...

if doesn't exist, INSERT

COMMIT

 

PS: This is the mysql forum.  Postgresql forum is over here: http://www.phpfreaks.com/forums/index.php/board,37.0.html

Link to comment
Share on other sites

Well juast add a unique key to the coloumn that you want it to be a unique value. Then you don't need to check it. PgSQL will not insert anything because of violation of keys and it will return false.

 

Also see the postgresql select statement syntax for further information.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.