Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Insuring unique data ? 2

Status
Not open for further replies.

admoore

IS-IT--Management
Joined
May 17, 2002
Messages
224
Location
US
I have a MySQL database which requires unique customer codes- I am trying to insure that when entering a new customer that you cannot duplicate an existing code. I thought that this would work; however it doesn't seem to do what I expected, that is, it rejects all codes entered... Can someone please help here???

TIA, here's my code:
Code:
$check = mysql_query("SELECT * FROM clients WHERE code = '$code' ",$linkid);

if ($check !==FALSE)
{
print &quot;<h3>The code $code is in use.  Try another code.</h3>&quot;;
exit;
}
 
so here's how I'd do what you're trying...

Code:
$check = mysql_query(&quot;....&quot;);
$num_rows = mysql_num_rows($check);

if ($num_rows > 0) {
  code is in use
}

But then again I wouldn't try to generate my own unique codes too often, I would recommend using the mySQL autoincrement field instead.

-Rob
 
admoore,

The mysql_query returns a resource id, not a count of records or anything else.
To get the number of records that have the code you are looking for you could do the following:

$result = mysql_query(&quot;SELECT * FROM clients WHERE code ='$code', $linkid);

# get the number of records (should be 0 for new code)
if (mysql_num_rows($result)>0){
... error message ...
}

You should also set up the table that the 'code' is a unique field and indexed. This makes it impossible to create a record with a duplicate key.
 
Thanks, I'd use auto-increment; however I need to use existing alpha-numeric codes already in use...

Thanks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top