Re: multiple fields all unique?
| From: | Jason Gerfen | Date: | Tue, 03 Feb 2004 21:09:23 +0000 |
| Subject: | Re: multiple fields all unique? | ||
| References: | 1 2 | Groups: | php.db |
| Request: | Send a blank email to php-db+get-32772@lists.php.net to get a copy of this message | ||
John W. Holmes wrote:
From: "Jas" <jason.gerfen@scl.utah.edu>Jas -- Jason Gerfen Student Computing Group Marriott Library University of Utah (801) 585-9810 jason.Gerfen@scl.utah.edu "I'm not a robot like you. I don't like having disks crammed into me... unless they're Oreos, and then only in the mouth." ~Phillip J. FryHas 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... Yeah, I have never used a unique field for the database, and you are right it is a mysql db.