By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,865 Members | 1,725 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,865 IT Pros & Developers. It's quick & easy.

how to maintain uniqueness in a mysql table

P: 57
i have blockname as a field. but i want it to be a unique one.

i tried with this code..[php]$check0=mysql_query("select count(*) from pms_block");
$num_rows0=mysql_num_rows($check0);
if($num_rows0>=1)
{
$check=mysql_query("select count(*) from pms_block where block_name='$bname'")or die('Unable to Select '.mysql_error());
$num_rows=mysql_num_rows($check);
if ($num_rows>0)
{
echo 'Block Name Already Exists. Give another Name<br /><a href="block_index.php">Please Try Again</a>';
exit;
}
}[/php]
but it doesn't work...when i give the second name as a different one... it shows please try again...it won't be inserted in the table...is there any other possible way to do this....please answer my question....
Apr 3 '08 #1
Share this Question
Share on Google+
2 Replies


ronverdonk
Expert 2.5K+
P: 4,258
You know this by now: next time you post code in a froum, enclose your posted code in [code] tags (See How to Ask a Question).

This makes it easier for our Experts to read and understand it. Failing to do so creates extra work for the moderators, thus wasting resources, otherwise available to answer the members' questions.

Please use [code] tags in future.

MODERATOR
Apr 3 '08 #2

Atli
Expert 5K+
P: 5,058
Hi.

You could go about this a different way...

You can tag any MySQL column as UNIQUE, making it impossible to insert the same piece of data twice. If you try to do so, MySQL will return an error.

So, creating a table, somewhat like this:
Expand|Select|Wrap|Line Numbers
  1. CREATE TABLE myTbl(
  2.   myID Serial Primary Key,
  3.   myName VarChar(255) Unique Not Null
  4. )
  5.  
You could do something like this:
Expand|Select|Wrap|Line Numbers
  1. // Connect MySQL
  2. #   You know the drill
  3.  
  4. // Insert name
  5. $sql = "INSERT INTO `myTbl`(`myName`) VALUES('$someValue')";
  6. $result = mysql_query($sql, $dbLink);
  7.  
  8. // Deal with the result
  9. if(!$result) {
  10.   echo "Name already taken";
  11. }
  12. else {
  13.   echo "Success!!";
  14. }
  15.  
There is no need to check if the name exits. Given that the query is valid, the query will only fail (under normal circumstances) if the name is a duplicate.

If you want to make sure the error is indeed because of a duplicate, rather than something else, you could always match the mysql_error() with the actual duplicate error.
Apr 3 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.