Re: multiple fields all unique?
| From: | Jas | Date: | Wed, 04 Feb 2004 15:18:52 +0000 |
| Subject: | Re: multiple fields all unique? | ||
| References: | 1 2 3 4 5 6 | Groups: | php.db |
| Request: | Send a blank email to php-db+get-32781@lists.php.net to get a copy of this message | ||
For this table to create 3 unique keys I did the following, in case it helps someone else out.
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |+----------+--------------+------+-----+---------+----------------+
| id | int(11) | | PRI | NULL | auto_increment | | hostname | varchar(100) | | | | | | mac | varchar(100) | | | | | | ip | varchar(100) | | | | | | vlan | varchar(100) | | | | |+----------+--------------+------+-----+---------+----------------+ UPDATE TABLE hosts ADD UNIQUE mac (mac); UPDATE TABLE hosts ADD UNIQUE hostname (hostname); UPDATE TABLE hosts ADD UNIQUE ip (ip); +----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |+----------+--------------+------+-----+---------+----------------+
| id | int(11) | | PRI | NULL | auto_increment | | hostname | varchar(100) | | UNI | | | | mac | varchar(100) | | UNI | | | | ip | varchar(100) | | UNI | | | | vlan | varchar(100) | | | | |+----------+--------------+------+-----+---------+----------------+ Now I have used the following to check if duplicate records exist before updating: <?php // Try and update with posted fields form html form $update = mysql_query("UPDATE hosts SET hostname='$_POST[hostname]', mac='$_POST[mac]', ip='$_POST[ip]', vlan='$_POST[vlan]' WHERE id='$_SESSION[id]'",$db); $rows = mysql_affected_rows(); // Check results of operation if($rows == 0) { echo "No matching records found"; } else { echo "Matching records found"; } Hope this helps anyone else, and thanks for the tip on MySQL's UNIQUE field, wish I would have known it sooner, I wouldn't be so pissed off from frustration. Jas