Re: multiple fields all unique?

From: Date: Tue, 03 Feb 2004 20:00:57 +0000
Subject: Re: multiple fields all unique?
References: 1  Groups: php.db 
Request: Send a blank email to php-db+get-32770@lists.php.net to get a copy of this message
From: "Jas" <jason.gerfen@scl.utah.edu> > Has anyone every performed such a feat as to check for matching fields > before updating? And if so could you show me some code that used to > accomplish this. I have written my own but the if - else statements are > getting ridiculous. Are the columns actually declared UNIQUE in your database? That's the first step. Then you can just do the update, and if it fails with a specific error, you know you've hit a duplicate. The long way to do it is to just SELECT the data first, then update if there are no matches (assuming MySQL, here, but the concept is the same) $query = "SELECT mac, ip FROM table WHERE mac = '{$_POST['mac']}' OR ip = '{$_POST['ip']}'"; $result = mysql_query($query) or die(mysql_error()); if($row = mysql_fetch_assoc($result)) { if($_POST['mac'] == $row['mac']) { echo "{$row['mac']} is already being used. "; } elseif($_POST['ip'] == $row['ip']) { echo "{$row['ip'] is already being used. "; } } else { $query = "UPDATE table SET mac = '{$_POST['mac']}', ip = '{$_POST['ip']}' WHERE hostname = '{$_POST['hostname']}'"; $result = mysql_query($query) or die(mysql_error)); echo "Record updated!"; } If you want an example of the first (and better) method, let me know. ---John Holmes...

« previous php.db (#32770) next »