I've got a table and I have a text field with a URL again, I don't want any rows with duplicate URL's but I'd rather not do a check before inserting, is there no way to make a text field unique or could you suggest another field type to use?
4 Answers
The solution is basically add a extra field on database like field_hash, make it VARCHAR and Index give unique.
CREATE TABLE 'info' (
'text' text NOT NULL,
'text_hash' varchar(40) NOT NULL,
PRIMARY KEY ('id'),
UNIQUE KEY 'text_hash' ('text_hash')
);
$text = 'Full Text';
$text_hash = sha1($text);
mysql_query("INSERT INTO info (text, text_hash) VALUES ('$text', '$text_hash')");
Comments
If your text field in the database is set to unique or a primary key or however you have it set up, than an insert statement will fail upon trying to input a duplicate. That way all you should have to do is properly handle the failed insert and there you have it.
As pointed out elsewhere, you can't have an actual TEXT field be unique, but if you are using a varchar field it is doable. This may not be important at all (may just be a miscommunication), because if you are storing URL's in a TEXT field, you have other problems to worry about as well.