如果已存在于数据库中,如何生成新的随机值?

How automatically generate new random value in textbox if the value already exist in database?

This is my example of my code.

<?php
$length = 1;
$randomString = substr(str_shuffle("123456789"), 0, $length);

$mysqli1 = new mysqli("localhost", "root", "", "k");

$sql = $mysqli1->query("SELECT catid FROM subcat WHERE catid = '$randomString'");
if(($sql->num_rows) > 0){
echo "User id exists already.";
}
echo '<input name="id" value="'.$randomString.'">';
?>

Thanks for advanced!

use this strtotime('now')

From W3schools : strtotime parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

This will always be unique.So there wont be any check needed.

Just in case if two user come simutaneously at a time,

Append a random string..for example:

$unique_id=strtotime('now')."".substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 5);

Clearly, you need an unique value

The uniqid() function generates a unique ID based on the microtime (current time in microseconds).

echo uniqid();

Edit: The OP want only 6 characters. So try something like

$id = uniqid();
$id = substr($id,rand(0,strlen($id) - 6),6);

This will be better, you can try this

$randomString = md5(uniqid(rand(), true));

A somewhat decently random string can be generated with this (Linux example):

substr(sha1(openssl_random_pseudo_bytes(3)), 0, 6);

Nonetheless, duplicates may occur due to the limited value domain; the following algorithm typically works:

  1. Generate identifier
  2. Insert record with generated identifier; use "INSERT IGNORE".
  3. If no affected rows, go to #1

Generate it again.

<?php
$length = 1;
$randomString = substr(str_shuffle("123456789"), 0, $length);

$mysqli1 = new mysqli("localhost", "root", "", "k");

$sql = $mysqli1->query("SELECT catid FROM subcat WHERE catid = '$randomString'");
if(($sql->num_rows) > 0){
    $randomString = substr(str_shuffle("123456789"), 0, $length);
}
echo '<input name="id" value="'.$randomString.'">';
?>

Or add a time at the end of the generated string to make it more random.

Something like this, and you should have a bigger length value. Because with length one, you can't have more random numbers.

substr(str_shuffle("123456789"), 0, $length).time();

But still there is chance of repeating unless you make a better algorithm using md5 or something.