Page 1 of 1

store in my sql only if not exists

Posted: Wed Oct 29, 2003 6:05 am
by yaron
hello all,

I have a unique field in a specific mysql table.
What I want is to build a function that gets this unique value and check if it exists in my table and only if not store it!

I want to find a smarter way than making 2 queries:
1. for checking if it exists
2.for storing

is that possible or I need to compremize?

Thanks

Posted: Wed Oct 29, 2003 6:41 am
by twigletmac
Stick with two queries, but the first one only needs to be simple:

Code: Select all

$sql = "SELECT key_field FROM table WHERE key_field=$value";
$result = mysql_query($sql) or die(mysql_error().'<p>'.$sql.'</p>');

if (mysql_num_rows($result) == 0) {
   // do the insert
} else {
    echo 'record already exists';
}
Mac