How to create random string and check if it exists form database , if it does create a new one using php.You can use php time() function to create random string and convert it using md5() function.
function rand_string(){ $string = substr(md5(time()), 0, 5); if(exists_in_db($string)) { // check in the db if exist, call again to this function $string = rand_string(); } return $string ; }
How to call to this function to get value.
$random = rand_string();
Note:exists_in_db()
is a function.You must write this function after getting parameter and it check in the database and return value.
function exists_in_db($val) { // get database connection first, then do this $sql = "SELECT id FROM table WHERE rand_val = '$val'"; $result = mysql_query($sql) or die(mysql_error()); $num_rows = mysql_num_rows($result) or die(mysql_error()); if($num_rows>0) { // exist this value in the db return true; } else { // not exist in the db return false; } }