store in my sql only if not exists

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

store in my sql only if not exists

Post 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
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post 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
Post Reply