Posted By

brownrl on 07/30/09


Tagged

sql php is name unique user


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

vali29
umang_nine
Envo


PHP isUnique


 / Published in: PHP
 

URL: http://www.goingson.be

A function that I use from time to time in order to make sure that a user name or something similar is not already in the database. Mainly just for user names though.

  1. // FUNCTION isUnique
  2. //
  3. // $table -> table to check
  4. // $field -> column to check
  5. // $value -> value to check
  6. // $except -> a clause to add to the mix.
  7. //
  8. // ex if( ! isUnique( "users" , "user_login" , "user1" );
  9. // ex if( ! isUnique( "users" , "user_login" , "user1" , "user_id != XX" );
  10.  
  11. function isUnique( $table , $field , $value , $except = null )
  12. {
  13.  
  14.  
  15. // build the query
  16. // value is escape cause maybe that comes from the user form
  17. // the rest should be coming from the programmer.
  18.  
  19. $q = "SELECT COUNT( ".$field." ) as total FROM ".$table." WHERE ".$field." = '".mysql_escape_string( $value )."'";
  20.  
  21.  
  22. // ok exception clause so lets just add it to the where
  23. // this probably gets used when a user does an update to their
  24. // user name...
  25. if( $except != null )
  26. {
  27. $q .= "' AND ".$except;
  28. }
  29.  
  30.  
  31. $qr = dbquery( $q );
  32. $total = $qr->fields['total'];
  33.  
  34. return $total == 0;
  35. }

Report this snippet  

You need to login to post a comment.